[Tutor] Command line args

Alan Gauld alan.gauld at btinternet.com
Tue Apr 10 09:38:23 CEST 2007

"Kirk Bailey" <deliberatus at verizon.net> wrote 

> Try:
>     filename=sys.arv[1]
> except Exception, e:

This still doesn't help for the problem where a 
different exception is raised.It really does need to be

try: filename = sys.argv[1]:
except IndexError:

>     if filename='':
>         filename='foo' # define a default value
>     else:
>         if foo: # detect one likely error
>             foobarcode
>     else:

This is invalid syntax it would need to be a chain of if/elif/else

> another idea is simply detect that there IS a argument;
> if sys.argv[1];
> filename=sys.argv[1]
> ...
> which avoids try altogether. Somehow I kinda like this way more.

This would still throw an exception if argv[1] doesn't exist 
because the code still tries to access non existent data. 
You cannot get away without using the try/except here 
unless you check the length of argv:

if len(sys.argv) > 1:
    filename = sys.argv[1]

Now you can check whether filename is valid or not.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list