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