passing arguments

Steven Bethard steven.bethard at gmail.com
Fri May 20 21:38:56 EDT 2005


James Stroud wrote:
> import sys
> 
> try:
>   arg1 = sys.argv[1]
> except IndexError:
>   print "This script takes an argument, you boob!"
>   sys.exit(1)

Also possible, to guarantee that exactly one argument was given:

try:
   arg1, = sys.argv
except ValueError:
   print "This script takes an argument, you boob!"
   sys.exit(1)

If you want to get, say, 3 arguments, just change that line to:

   arg1, arg2, arg3 = sys.argv

> OR, way better: See the optparse module.

Definitely.  Though depending on what kind of arguments your script 
takes, you still may need to deal with the args that optparse returns.

STeVe



More information about the Python-list mailing list