[Tutor] Testing for commandline args

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat May 14 03:40:30 CEST 2005


>
> If I have arguments, the "different stuff" happens beautifully, thank
> you very much.  If I don't have arguments I get this:
>
> if sys.argv[1]:
> IndexError: list index out of range]
>
> So I'm doing something wrong.  I looked at getopt, but that seemed to be
> doing what I was already doing, except in a way I could not follow :-(


Hi William,

One difference between Python and Perl is their treatment of out-of-bound
indices on lists.  Python does not "autovivify" a list, nor does it
automagically extend lists to make indices fit.  So if there are no
command line arguments, doing:

    sys.argv[1]

will raise the IndexError exception that you're seeing.  It is a
significant difference between those two languages, so be careful.


There are several ways of doing what you're doing.  One solution is to
check for list length, as Max suggests.  Another is to take a "slice" of
the argument list:

    if sys.argv[1:]: ...

The expression:

   sys.argv[1:]

produces a list of all but the first entry in sys.argv.  And the condition
check should work fine because empty lists are treated as False in Python.



Best of wishes!



More information about the Tutor mailing list