- So far I've only been using optparse.OptionParser so I do the
following:
from optparse import OptionParser
- Define a usage string. I've been using:
usage = "Usage: %prog [options]" - Define a parser: parser = OptionParser( usage = usage )
- Set the defaults: parser.set_defaults( somevar = defaultvalue )
- Add options:
- Example of command line options that have arguments:
parser.add_option(
"--someopt",
action="store",
dest="someoptname",
help="help info for --someopt" ) - Example of command line option that acts as a switch/toggle:
parser.add_option(
"--turniton",
action="store_true",
dest"turnitonflag",
help="help for turniton" ) - Another useful argument is metavar - helps you to name the variable being addressed by the option. The default is ok.
- Example of command line options that have arguments:
- Get the options and arguments:
(options, args) = parser.parse_args() - At this point it all depends on what you want to do. Let's say we want to access the options defined above:
- To access someoptname:
someoptname = options.someoptname - To access turnitonflag and store in a differently named variable:
myturnitonflag = options.turnitonflag - You get the picture.
- To access someoptname:
- You can use parser.error( "some message to indicate what went wrong" ) to convey to user that the options didn't work.
Wednesday, September 23, 2009
python optparse mini tutorial / how to
Here's a little tutorial on how to use the optparse module in the Python standard library.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment