User Tools

Site Tools


python:optparse

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
python:optparse [2010/03/15 12:04] – created tkbletscpython:optparse [2011/06/05 17:40] (current) tkbletsc
Line 1: Line 1:
 <code python> <code python>
 +from optparse import OptionParser
 +
 things = { things = {
         'this_thing': this,         'this_thing': this,
Line 6: Line 8:
 } }
 parser = OptionParser("Usage: %prog [options] <files ...>") 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("-n", "--number", dest="number", help="Quantity of things", metavar="NUM", type="int")
Line 19: Line 24:
         sys.exit(0)         sys.exit(0)
  
-bits = options.bits+num = options.number
 thing = things[option.thing] thing = things[option.thing]
 if options.verbose: verbose_write = lambda s: sys.stderr.write(s) if options.verbose: verbose_write = lambda s: sys.stderr.write(s)
 else:               verbose_write = lambda s: 0 else:               verbose_write = lambda s: 0
 +</code>
 +
 +Shorter:
 +<code=python>
 +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)
 + 
 </code> </code>
python/optparse.1268679893.txt.gz · Last modified: 2010/03/15 12:04 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki