User Tools

Site Tools


python:optparse

Differences

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

Link to this comparison view

python:optparse [2013/03/16 17:41] (current)
Line 1: Line 1:
 +==== Deal with command line arguments using OptionParser ====
 +07.02.2011
  
 +
 +Check the code below (self explanatory):​
 +
 +<code python>
 +#​!/​usr/​bin/​env python
 +# -*- coding: utf-8 -*-
 +
 +import optparse
 +import os
 +
 +PROGRAM = "​example_script"​
 +VERSION = "0.1 alpha"
 +DESCRIPTION = "Here is some description of what this script can do (or not)"
 +
 +
 +def main():
 +    p = optparse.OptionParser(description = DESCRIPTION,​
 +                              prog = PROGRAM, ​
 +                              version = VERSION,
 +                              usage = "%prog [OPTIONS] argument"​)
 +    p.add_option('​--file',​ '​-f',​ action="​store",​ type="​string",​ dest="​filename"​)
 +    p.add_option("​-n", ​
 +                type="​int",​ dest="​n_integer",​
 +                help = "For integer arguments"​)
 +    p.add_option("​-s", ​
 +                type = "​float",​ dest = "​n_float",​
 +                help = "For float arguments"​)
 +    p.add_option("​-v",​ "​--verbose",​
 +                action = "​store_true",​ dest = "​verbose",​ default=False,​
 +                help = "Set this if you want verbose results"​)
 +    (options, arguments) = p.parse_args()
 +    ​
 +    if len(arguments) == 1:
 +        print "​Argument was %s" % (arguments[0],​)
 +
 +        print "​Integer option -> %d" % (options.n_integer,​ )
 +        print "Set verbose? %s" % (options.verbose,​ )
 +
 +    else:
 +        p.print_help()
 +
 +
 +
 +if __name__ == '​__main__':​
 +    main()
 +</​code>​
 +
 +
 +
 +
 +References:
 +
 +[[http://​docs.python.org/​library/​optparse.html | Full Documentation ]]
python/optparse.txt ยท Last modified: 2013/03/16 17:41 (external edit)