Tuesday, January 19, 2010

Python command line arguments

It's become clear to me that I need to learn more about the Python standard library. Lots of great stuff has been added. I did dir(str) today and saw methods that I never knew about.

In that vein, here is a short demo of optparse (docs). It should give you a good feeling for what's available (of course, there is more):

from optparse import OptionParser
parser = OptionParser()
parser.add_option('-f', '--file', dest='fn',
help='write report to FILE', metavar='FILE')
parser.add_option('-q', '--quiet',
action='store_false', dest='v', default=True,
help="don't print status messages to stdout")
parser.add_option('-n',
dest='n', type='int',
help="need to input a number")

options, args = parser.parse_args()
print options,
if args: print args,
print

We can exercise it like this:

$ python options.py -f xyz
{'n': None, 'fn': 'xyz', 'v': True}
n$ python options.py -f xyz abc def
{'n': None, 'fn': 'xyz', 'v': True} ['abc', 'def']
$ python options.py -fxyz
{'n': None, 'fn': 'xyz', 'v': True}
$ python options.py --file=xyz
{'n': None, 'fn': 'xyz', 'v': True}
$ python options.py -q
{'n': None, 'fn': None, 'v': False}
$ python options.py -n
Usage: options.py [options]

options.py: error: -n option requires an argument
$ python options.py -n 7
{'n': 7, 'fn': None, 'v': True}
$ python options.py --help
Usage: options.py [options]

Options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to stdout
-n N need to input a number