Wednesday, 6 November 2019

arcpy - CalculateField_management, python Toolbox


I am trying to fill a field and I am using arcpy's CalculateField_management function.


I want to fill the new field with the name of the shapefile, so I am using arcpy.Describe. But when I run the script I get this error: ExecuteError: ERROR 000539: Error running expression: PRUEBAS Traceback (most recent call last): File "", line 1, in NameError: name 'PRUEBAS' is not defined. 'Pruebas' is the name of the shapefile, I obtain it from desc.baseName


The code is:


import arcpy, os, sys
from arcpy import env
from arcpy import Describe


class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = ""

# List of tool classes associated with this toolbox
self.tools = [Tool]


class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "FIELD"
self.description = ""
self.canRunInBackground = False

def getParameterInfo(self):
"""Define parameter definitions"""


# First parameter

param0 = arcpy.Parameter(
displayName="Shape entrada",
name="in_features",
datatype="DEShapefile",
parameterType="Required",
direction="Input")


# Second parameter

param1 = arcpy.Parameter(
displayName="Nuevo campo",
name="field",
datatype="Field",
parameterType="Required",
direction="Input")

parameters = [param0, param1]

return parameters

def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):return
def updateMessages(self, parameters):return
def execute(self, parameters, messages):
"""The source code of the tool."""
a= parameters[0].valueAsText

b= parameters[1].valueAsText

desc = arcpy.Describe(parameters[0])
a=arcpy.AddField_management(a, b, "TEXT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

a=arcpy.CalculateField_management(a, b, desc.baseName,"PYTHON_9.3",code_block="")

return a

`




Answer



In the CalculateField_management you are giving the desc.baseName as the expression parameter. It assumes the value of that variable is the name of a function that is not defined.


This should work:



arcpy.CalculateField_management(a, b, '"%s"' % desc.baseName)



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...