IndexError list out of range

4388
5
03-08-2015 03:15 PM
PROBERT68
Frequent Contributor
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

>>>

0 Kudos
5 Replies
DarrenWiens2
MVP Honored Contributor

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.

0 Kudos
DanPatterson_Retired
MVP Emeritus

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])

0 Kudos
PROBERT68
Frequent Contributor

@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..

0 Kudos
DarrenWiens2
MVP Honored Contributor

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).

  1. import arcpy, sys 
  2. workspace = r'C:/someworkspace' 
  3. featureclass = r'C:/somefolder/someGDB.gdb/somefeatureclass'
  4. try: 
  5.   arcpy.env.workspace = workspace 
  6.   fields = arcpy.ListFields(featureclass) 
  7. for fld in fields: 
  8. print fld   
  9. except:   
  10. print arcpy.GetMessages() 
0 Kudos
DanPatterson_Retired
MVP Emeritus

​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

0 Kudos