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.
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
).
#!/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)
usage: script.py [-h] [--foo [bar]] $ script.py -> foo=baz $ script.py --foo -> foo=None $ script.py --foo bar -> foo=bar
Also, note that the standard library also has optparse, a more powerful options parser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With