views:

158

answers:

6

I would like to be able to parse command line arguments in my python 2.6 program.

Ideally, I want to be able to handle these cases:

# show some help
./myprogram --help

# these are equivilent
./myprogram --block=1
./myprogram -b 1

# this means verbose, and twice as verbose:
./myprogram -v
./myprogram -vv
A: 

Is this what you are looking for?

inspectorG4dget
+2  A: 

Python has argument processing built in, with the getopt module.

It can handle long and short forms of arguments as well as "naked" and parameterised versions (--help versus --num=7).

For your specific use cases (with a little more), you'd probably be looking at something like:

opts,args = getopt.getopt(argv,"b:vVh",["block=", "verbose", "very-verbose", "help"])

I'm not sure off the top of my head if it allows multi-character single-hyphen variants like -vv. I'd just use -v and -V myself to make my life easier.

paxdiablo
+16  A: 

Check out the argparse module (or optparse for older Python versions).
Note that argparse/optparse are newer, better replacements for getopt, so if you're new to this they're the recommended option. From the getopt docs:

Note The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.

tzaman
And by "older Python versions", he means every version that was released more than 8 days ago.
Forest
@Forest - shhhh, we're in the future now! ;)
tzaman
+1  A: 

A better option than that link is the modules OptParse or GetOpt, and depending on which version of python you're using, the newest ones..2.7, and 3.1.2, have an even newer module built in. The documentation on the official python.org reference has a very informative set of documentation and examples for those modules. If you go to python.org and just do a quick search for OptParse or GetOpt, you'll have everything you need.

Stev0
+1  A: 

optfunc is an interesting little module. It's great if you want to quickly write a little script. For larger things I would go with argparse as others wrote.

Tomek Szpakowicz
A: 

There might be a better way but I would just uses sys.argv and put in conditionals wherever needed i.e.

if '--v' or '--vv' in sys.argv :
    print 'verbose message'
Ryan Jenkins