I created a small arcpy script tool which works fine when I run it from ArcMap. All it does is list the fields from a specified layer.
import arcpy
myLayer = arcpy.GetParameter(0)
fieldList = arcpy.ListFields(myLayer)
for field in fieldList:
arcpy.AddMessage(field.name)
However if I create a Python Toolbox with this same script, it fails on fieldList = arcpy.ListFields(myLayer)
with this error:
Traceback (most recent call last):
File "<string>", line 37, in execute
File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\__init__.py", line 1131, in ListFields
return gp.listFields(dataset, wild_card, field_type)
File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\geoprocessing\_base.py", line 344, in listFields
self._gp.ListFields(*gp_fixargs(args, True)))
IOError: "" does not exist
Failed to execute (TestPYTListFields).
If I replace fieldList = arcpy.ListFields(myLayer)
with fieldList = arcpy.Describe(myLayer).fields
it works as expected.
Why does my ListFields()
fail from a Python Toolbox, and what can I put in place to make it work?
I suspect it may be something to do with the Feature Layer object, as I'm also having Search Cursors fail when referencing the Feature layer objects as well, although I haven't tested that to the same extent as the ListFields.
Below is my entire PYT:
import arcpy
class Toolbox(object):
def __init__(self):
self.label = u'ListFields'
self.alias = ''
self.tools = [TestPYTListFields]
class TestPYTListFields(object):
def __init__(self):
self.label = u'TestPYTListFields'
self.description = u''
self.canRunInBackground = False
def getParameterInfo(self):
param_1 = arcpy.Parameter()
param_1.name = u'Input_Layer'
param_1.displayName = u'Input Layer'
param_1.parameterType = 'Required'
param_1.direction = 'Input'
param_1.datatype = u'Feature Layer'
return [param_1]
def isLicensed(self):
return True
def updateParameters(self, parameters):
return
def updateMessages(self, parameters):
return
def execute(self, parameters, messages):
import arcpy
myLayer = parameters[0]
fieldList = arcpy.ListFields(myLayer) # ListFields doesn't work from PYT
#fieldList = arcpy.Describe(myLayer).fields # Describe().fields does work from PYT
for field in fieldList:
messages.AddMessage(field.name)
return