[Tutor] arg exceptions for scrips

Wesley Chun wesc@deirdre.org
Sat, 14 Jul 2001 23:10:11 -0700 (PDT)


another thing you can do to make your program more robust is
to determine whether the input/source file exists and to print
out an error message like:  'file1' does not exist, try again
or something like that, then perhaps give the usage string.

without this code, your script will crap out again with an
exception, also somewhat useless to the user.

just another thought,

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall PTR, December 2000
    http://starship.python.net/crew/wesc/cpp/

wesley.j.chun :: wesc@baypiggies.org
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/


On Sat, 14 Jul 2001, kevin parks wrote:
>
> Oh, dopey me! I looked right past that thinking anticipating what that problem was. So what i really want is:
>
> if len(sys.argv) != 3:
>
> and not:
>
> if len(sys.argv) != 2:
>
> Thank you!
>
> On Fri, 13 Jul 2001 11:01:26
>  George Gates wrote:
> >
> >>if __name__ == '__main__':
> >>         if len(sys.argv) < 2:
> >>                 print "Usage:", sys.argv[0], "infile outfile"
> >>                 sys.exit(1)
> >>         else:
> >>                 cp(sys.argv[1],sys.argv[2])
> >
> >The problem is the test of the length should be less than 3, not less than
> >2.  If you executed with only one argument the length of sys.argv would be
> >2, sys.argv[0] for the script name, sys.argv[1] for the argument:
> >
> >ggates@ggates ggates]$ more arg_count.py
> >
> >#!/usr/bin/env python
> >import sys
> >print "The number of arguments are %s: %s" % (len(sys.argv),sys.argv)
> >
> >[ggates@ggates ggates]$ ./arg_count.py file1
> >
> >The number of arguments are 2: ['./arg_count.py', 'file1']