tags:

views:

424

answers:

5

I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:

> script.py --foo
> script.py --foo=bar

From the Python getopt docs it seems I have to choose one or the other.

+3  A: 

Also, note that the standard library also has optparse, a more powerful options parser.

Ned Batchelder
optparse documentation explicitly states it does NOT support arguments with optional values (for good reason)
Triptych
+1  A: 

Use the optparse package.

Seth
+3  A: 

check out argparse: http://code.google.com/p/argparse/

especially the 'nargs' option

Kevin Horn
+2  A: 

There isn't an option in optparse that allows you to do this. But you can extend it to do it:

http://docs.python.org/library/optparse.html#adding-new-actions

Santi
+1  A: 

optparse module from stdlib doesn't support it out of the box (and it shouldn't due to it is a bad practice to use command-line options in such way).

As @Kevin Horn pointed out you can use argparse module (installable via easy_install argparse or just grab argparse.py and put it anywhere in your sys.path).

Example

#!/usr/bin/env python
from argparse import ArgumentParser

if __name__ == "__main__":
    parser = ArgumentParser(prog='script.py')
    parser.add_argument('--foo', nargs='?', metavar='bar', default='baz')

    parser.print_usage()    
    for args in ([], ['--foo'], ['--foo', 'bar']):
        print "$ %s %s -> foo=%s" % (
            parser.prog, ' '.join(args).ljust(9), parser.parse_args(args).foo)

Output

usage: script.py [-h] [--foo [bar]]
$ script.py           -> foo=baz
$ script.py --foo     -> foo=None
$ script.py --foo bar -> foo=bar
J.F. Sebastian