[Tutor] Testing for commandline args

William O'Higgins william.ohiggins at utoronto.ca
Sat May 14 02:30:56 CEST 2005


I am writing a tiny commandline utility (re-writing it from Perl) and I
want the behaviour to change based on the presence of arguments.  The
conditional in Perl looks like this:

if (defined $ARGV[0]) {
    do stuff
} else {
    do different stuff

In Python I've nearly been successful, but something's wonky.  Here's
the code:

if sys.argv[1]:
    do stuff
else:
    do different stuff

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 :-(

Any tips would be appreciated, thanks.
-- 

yours,

William

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20050513/51bc0d05/attachment.pgp


More information about the Tutor mailing list