Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The optparse Module

The command line arguments from the operating system are put into the sys.argv variable as a sequence of strings. Looking at the syntax rules for command line options and operands in the previous section we can see that it can be challenging to parse this sequence of strings.

The optparse module helps us parse the options and operands that are provided to our program on the command line. This module has two very important class definitions: OptionParser and Values.

An OptionParser object does two things:

  • It contais a complete map of your options, operands and any help strings or documentation. This module can, therefore, produce a complete, standard-looking command synopsis. The -h and --help options will do this by default.

  • It parses the sys.argv[1:] list of strings and creates a Values object with the resulting option values.

The OptionParser has the following methods and attributes. There are a number of features which are used by applications which need to create a specialized subclass. We'll focus on the basic use case and ignore some of the features focused on extensibility.

OptionParser

The constructor for an optparse.OptionParser has a number of keyword arguments that can be used to define the program's options.

usage

This keyword parameter sets the usage summary that will print when the options cannot be parsed, or help is requested. If you don't provide this, then your program's name will be taken from sys.argv[0]. You can suppress the usage information by setting this to the special constant optparse.SUPPRESS_USAGE.

version

This keyword parameter provides a version string. It also adds the option of -version which displays this string. This string can contain the formatting characters %prog which will be replaced with the program's name.

description

A paragraph of text with an overview of your program. This is displayed in respose to a help request.

add_help_option

This is True by default; it adds the -h and -help options. You can set this to False to prevent adding the help options.

prog

The name of your program. Use this if you don't want sys.argv[0] to be used.

add_option( string , keywords )

This method of an OptionParser defines an option. The positional argument values are the various option strings for this option. There can be any mixture of short (-X) and long (--long) option strings. This is followed by any number of keyword arguments to provide additional details about this option. It is rare to have multiple short option strings for the same option.

For example, add_option( "-o", "--output", "-w", dest="output_file", metavar="output" ) defines three different variations that set a single destination value, output_file. In the help test, the string "output" will be used to identify the three alternative option strings.

action

This keyword parameter defines what to do when this option appears on the command line. The default action is "store". Choices include "store", "store_const", "store_true", "store_false", "append", "count", "callback" and "help". The store actions store the option's value. The append action accumulates a list of values. The count simply counts occurances of the option. Count is often used so that -v is verbose and -vv is even more verbose.

type

This keyword parameter defines what type of value this option uses. The default type is "string". Choices include "string", "int", "long", "choice", "float" and "complex".

dest

This keyword parameter defines the attribute name in the OptionParse object that will have the final value. If you don't provide a value, then the first long option name will be used. If you didn't provide any long option names, then the first short option name will be used.

nargs

This keyword parameter defines how many values are permitted for this option. The default value is 1. If this value is more than 1, then a tuple is created to contain the sequence of values.

const

If the action was "store_const", this keyword parameter provides the constant value which is stored.

choice

If the type was "choice", this is a list of strings that contain the valid choices. If the option's value is not in this list, then this is a run-time error. This set of choices is displayed as the help for this option.

help

This keyword parameter provides the help text for this option.

metavar

This keyword parameter provides the option's name as shown to the user in the help documentation. This may be different than the abbreviations chosen for the option.

callback

If the action was "callback", this is a callable (either a function or a class with a __call__ method) that is called. This is called with four positional values: the Option object which requested the callback, the command line option string, the option's value string, and the overall OptionParser object.

callback_args, callback_kwargs

If the action was "callback", these keyword parameters provide the additional arguments and keywords used when calling the given function or object.

set_defaults keywords

This method of an OptionParser provides an option's default value. Each keyword parameter is a destination name. These must match the dest names (or the the option string) for each option that you are providing a default value.

parse_args( args , values ) → ( options, operands )

This method will parse the provided command-line argument strings and update a given optparse.Values object. By default, this will parse sys.argv[1:] so you don't need to provide a value for the args parameter. Also, this will create and populate a fresh optparse.Values object, so you don't need to provide a value for the values parameter.

The usual call form is options, operands = myParser.parse_args().

A Values object is created by an OptionParser. It only has attribute values. The attributes are defined by the options seen during parsing and any default settings that were provided to the OptionParser.

A Complete Example. Here's a more complete example of using optparse. Assume we have a program with the following synopsis.

portfolio.py 〈-v〉 〈-h〉 〈-d mm/dd/yy 〉 〈-s symbol ...〉 file

This program has two single-letter options: -v and -h. It has two options which take argument values, -d and -s. Finally, it accepts an operand of a file name.

These options can be processed as follows:

"""portfolio.py -- examines a portfolio file
"""
import optparse
class Portfolio( object ):
    ...

def main():
    portfolio= Portfolio()
    oparser= optparse.OptionParser( usage=__doc__ )
    oparser.add_option( "-v", action="count", dest="verbose" )
    oparser.add_option( "-d", dest="date" )
    oparser.add_option( "-s", dest="symbol" )
    oparser.set_defaults( verbose=0, date=None, symbol="GE" )
    options, operands = oparser.parse_args()
    portfolio.date= options.date
    portfolio.symbol= options.symbol
    for f in operands:
        portfolio.process( f )

if __name__ == "__main__":
    main()

The program's options are added to the parser. The default values, similarly are set in the parser. The parse_args function separates the the options from the arguments, and builds the options object with the defaults and the parsed options. The process function performs the real work of the program, using the options and operands extracted from the command line.


 
 
  Published under the terms of the Open Publication License Design by Interspire