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.

  1. So far I've only been using optparse.OptionParser so I do the

    from optparse import OptionParser

  2. Define a usage string. I've been using:

    usage = "Usage: %prog [options]"

  3. Define a parser: parser = OptionParser( usage = usage )

  4. Set the defaults: parser.set_defaults( somevar = defaultvalue )

  5. Add options:

    1. Example of command line options that have arguments:

      help="help info for --someopt" )

    2. Example of command line option that acts as a switch/toggle:

      help="help for turniton" )

    3. Another useful argument is metavar - helps you to name the variable being addressed by the option. The default is ok.

  6. Get the options and arguments:

    (options, args) = parser.parse_args()

  7. 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.

  8. You can use parser.error( "some message to indicate what went wrong" ) to convey to user that the options didn't work.

No comments: