getopt

Mark Borgerding mborgerding at cinci.rr.com
Mon Nov 17 19:39:03 EST 2003


Don Low wrote:

> 	options, xarguments = getopt.getopt(sys.argv[1:], 'ha', \
[snip]
> When I execute the script with the -a option or the --view option as in:
> 
> ./script_name -a myarg
> 
> It should report back:
> 
> -a = myarg
> 



The second argument should have a colon after any letter/option that 
takes an argument.


Also, a useful trick is to cast the opts to a dict.  This prevents the 
need for iterating over the opts and allows for concise definition of 
default arguments.

e.g.


opts,args = getopt.getopt(sys.argv[1:] , 'h:a:v' )
opts = dict(opts)

hparm = opts.get('-h','cutie')
aparm = float( opts.get( '-a', math.pi  ) )
verbose = opts.has_key('-v')


Caveats: the dict trick does not allow an option to be specified more 
than once (e.g. -vv), it also loses ordering.


- Mark





More information about the Python-list mailing list