User Tools

Site Tools


python:optparse

Differences

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

Link to this comparison view

Both sides previous revision Previous revision
python:optparse [2011/03/03 11:31]
tkbletsc
python:optparse [2011/06/05 17:40] (current)
tkbletsc
Line 28: Line 28:
 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.txt ยท Last modified: 2011/06/05 17:40 by tkbletsc