Error when importing python script (IndexError: list index out of range)

5910
1
08-29-2012 05:51 AM
JohnChurchill
New Contributor III
Hi,

     I'm converting some of my pre-existing python scripts (that worked in version 9.3.1) to work with version 10 (and python 2.6). I have a script that has 3 arguments and a function. It works fine in 9.3.1 but in 10.0 (python 2.6) it is giving me an error when I simply try to import the script ...

>>> from ExportIndividualFeatures2_v10 import ExpIndFeatures
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "ExportIndividualFeatures2_v10.py", line 23, in <module>
    inWorkspace = sys.argv[1]
IndexError: list index out of range

Again, this error occurs when trying to simply import the script at the command line in PythonWin (see the command issued after the ">>>" above)

The relevant parts of the script I am importing are these lines at the beginning ...

import sys, string, os, arcpy

inWorkspace = sys.argv[1]
inShapeFile = sys.argv[2]
inField = sys.argv[3]

def ExpIndFeatures(inWorkspace, inShapeFile, inField):
    try:
        etc. etc. (code in here)


Why does this work with 9.3.1 (python 2.52 pywin 32 build 210) and not with 10.0 (python 2.6 pywin 32 build 212) ???
Tags (2)
0 Kudos
1 Reply
MikeHunter
Occasional Contributor
When you import a python module, the interpreter executes any code in the outer scope (code not inside functions or not protected like the example below.  This is true for 2.7 and was true in 2.5.  So when you get to the sys.argv calls, an exception occurs, since anything past sys.argv[0] is passed by a command line.  What you need to do is put your code in function(s) and then slice sys.argv  below an if __name__  == '__main__' line, like so:


import sys, string, os, arcpy

def ExpIndFeatures(inWorkspace, inShapeFile, inField):
    try:
        etc. etc. (code in here)

if __name__ == '__main__':

    inWorkspace = sys.argv[1]
    inShapeFile = sys.argv[2]
    inField = sys.argv[3]

    result = ExpIndFeatures(inWorkspace, inShapeFile, inField)




What the if __name__ == '__main__' part does is keep any code it below from executing unless the module is run as a script.  Do this, and you will be able to import your module without an exception, and you can then call ExpIndFeature with args.  There are other ways of doing this, but the example above is a standard python idiom.  And it's practical, since it makes your module dual-purpose as either an importable module or an executable script.

good luck
Mike
0 Kudos