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

Steven Bethard steven.bethard at
Wed Oct 4 00:28:36 CEST 2006

erikwickstrom at 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]
         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::


     $ 3.14159265359

     $ -h
     usage: [-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:


More information about the Python-list mailing list