import arcpy, sys workspace = sys.argv[1] featureclass = sys.argv[2] try: arcpy.env.workspace = workspace fields = arcpy.ListFields(featureclass) for fld in fields: print fld except: print arcpy.GetMessages()
The error I am getting is :
>>>
Traceback (most recent call last):
File "C:\ArcpyBook\Appendix1\ListFields.py", line 3, in <module>
workspace = sys.argv[1]
IndexError: list index out of range
>>>
Have you collected any parameters in sys.argv[]? The error indicates you have not. You can check with:
print len(sys.argv)
This should return 1 (which holds the name of the script) if no extra parameters have been specified.
also line 14 isn't indented properly
and as Darren says...how are you running this? you don't show what you used as an input? add in a couple of print statements so you can see the script name (ie sys.argv[0]) and the inputs (ie sys.argv[1])
@Dan Patterson
Sorry, this code came from the book I am working on from Eric Pimpler's ebook "Programming ArcGIS 10.1 with Python cookbook. That book was in 2013
Yes I find a lot of errors in that book however I tried to tweak some of the codes but was not able to figure it out and I thought there must be a way around to correct it..
This code is meant to be run from a script tool with two parameters: workspace and feature class.
For your purposes, you can just enter values for each parameter (sorry, the code block won't let me format it correctly, so there are some indentation issues, but substituting values for the sys.argv parameters is the take-home message).
- import arcpy, sys
- workspace = r'C:/someworkspace'
- featureclass = r'C:/somefolder/someGDB.gdb/somefeatureclass'
- try:
- arcpy.env.workspace = workspace
- fields = arcpy.ListFields(featureclass)
- for fld in fields:
- print fld
- except:
- print arcpy.GetMessages()
or if using your favorite IDE, check how you can enter parameters while running them. I know Pythonwin pops up a dialog and you can enter the parameters directly so you don't need to hardcode them in a script