User Tools

Site Tools


python:optparse
from optparse import OptionParser
 
things = {
        'this_thing': this,
        'that_thing': that,
        'the_other': get_the_other(),
}
parser = OptionParser("Usage: %prog [options] <files ...>")
 
# uncomment if you need to ignore options after the first argument, e.g. "mywrapper -x ls -l"
# parser.disable_interspersed_args()
 
parser.add_option("-n", "--number", dest="number", help="Quantity of things", metavar="NUM", type="int")
parser.add_option("-h", "--host", dest="hostname", help="Hostname. Default: %default", metavar="HOST", default="localhost")
parser.add_option("-s", "--sort", dest="sort", help="Sort by the given key.  One of: length,name.", metavar="KEY", type="choice", choices=['length','name'])
parser.add_option("-v", "--verbose", dest="verbose", help="Print extra info.", action="store_true")
parser.add_option("-t", "--thing", dest="thing", help="What are we looking for?  One of %s." % targets.keys(), type="choice", choices=targets.keys(), default="this_thing")
 
(options, args) = parser.parse_args()
 
if (len(args)<=0):
        parser.print_help()
        sys.exit(0)
 
num = options.number
thing = things[option.thing]
if options.verbose: verbose_write = lambda s: sys.stderr.write(s)
else:               verbose_write = lambda s: 0

Shorter:

from optparse import OptionParser
 
parser = OptionParser("Usage: %prog [options] <files ...>")
 
parser.add_option("-n", "--number", dest="number", help="Quantity of things", metavar="NUM", type="int")
parser.add_option("-h", "--host", dest="hostname", help="Hostname. Default: %default", metavar="HOST", default="localhost")
parser.add_option("-s", "--sort", dest="sort", help="Sort by the given key.  One of: length,name.", metavar="KEY", type="choice", choices=['length','name'])
parser.add_option("-v", "--verbose", dest="verbose", help="Print extra info.", action="store_true")
 
(options, args) = parser.parse_args()
 
if (len(args)<=0):
        parser.print_help()
        sys.exit(0)
 
python/optparse.txt · Last modified: 2011/06/05 17:40 by tkbletsc