Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command line options with optional arguments in Python

Tags:

python

getopt

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.

like image 407
Brian Hawkins Avatar asked Dec 17 '22 05:12

Brian Hawkins


2 Answers

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
like image 60
jfs Avatar answered Feb 11 '23 11:02

jfs


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

like image 32
Ned Batchelder Avatar answered Feb 11 '23 12:02

Ned Batchelder