Can't get around "IndexError: list index out of range"

Steven Bethard steven.bethard at gmail.com
Tue Oct 3 18:28:36 EDT 2006


erikwickstrom at gmail.com wrote:
> I'm trying to get this bit of code to work without triggering the
> IndexError.
> 
> import shutil, os, sys
> 
> if sys.argv[1] != None:
>     ver = sys.argv[1]
> else:
>     ver = '2.14'

Something like::

     if len(sys.argv) > 1:
         ver = sys.argv[1]
     else:
         ver = '2.14'

It looks like you're trying to do argument parsing, though and for 
anything more complicated than the above, you might prefer to use a real 
argument parsing library like argparse_::

     import argparse

     parser = argparse.ArgumentParser(description='print the version')
     parser.add_argument('ver', nargs='?', default='2.14',
                         help='the version number to print')

     args = parser.parse_args()
     print args.ver

Then from the command line::

     $ script.py
     2.14

     $ script.py 3.14159265359
     3.14159265359

     $ script.py -h
     usage: script.py [-h] [ver]

     print the version

     positional arguments:
       ver         the version number to print

     optional arguments:
       -h, --help  show this help message and exit

And then you can feel good about yourself for also documenting your 
command-line interface. ;-)

.. _argparse: http://argparse.python-hosting.com/

STeVe



More information about the Python-list mailing list