Previous Page
Next Page

8.10. The optparse Module

The optparse module offers rich, powerful ways to parse the command-line options (a.k.a. flags) that the user passed upon starting your programs (by using syntax elements such as -x or --foo=bar on the command line, after your program name and before other program arguments). Instantiate (without arguments) the OptionParser class supplied by the module, populate the instance so it knows about your program's options (by calls to its add_option method), and finally call the instance's parse_args method to handle your program's command line, dealing with each option appropriately and returning the collection of option values and a list of nonoption arguments.

optparse supports many advanced ways to customize and fine-tune your program's option-parsing behavior. In most cases, you can accept optparse's reasonable defaults and use it effectively with just the two methods of class OptionParser that I cover here (omitting many advanced options of these methods, which you do not normally need). For all of the powerful and complex details, consult Python's online docs.

An OptionParser instance p supplies the following methods.

add_option

p.add_option(opt_str,*opt_strs,**kw)

The positional arguments specify the option strings, i.e., the strings that the user passes as part of your program's command line to set this option. Each argument can be a short-form option string (a string starting with a single dash [hyphen] followed by a single letter or digit) or a long-form option string (a string starting with two dashes followed by an identifier that may also contain dashes). You normally pass exactly one short-form and one long-form option string, but it's also okay to pass multiple "synonyms," or just short forms, or just long forms.

The named (optional) arguments (kw) are where the action is...literally, too, because the most important argument is the named one, action, with a default value of 'store', which specifies that the value associated with the option string gets bound as an attribute of the options-object, which method parse_args returns.

'store' implies that if the user who starts your program supplies this option at all, then the user must also supply a value associated with this option. If the user does not pass the option at all, the associated attribute of the options-object gets set to None. To use a different default value, include in the call to add_option a named argument such as default='foo' (this uses 'foo' as the default value for the attribute). If the user does pass the option, it must be followed by a value to associate with it. The value can be the immediately following command-line argument, or can be juxtaposed to the option string as part of the same argumentjust concatenated, for a short-form option string, or concatenated with an = in between for a long-form option string. Otherwise, parse_args will emit an error message and raise a SystemExit exception.

The name of the option-object's attribute associated with an option is the identifier in its first long-form option string (with dashes, if any, replaced by underscores), or the single letter in the first short-form option string if the option has no long form. To use a different name for the attribute, include in the call to add_option a named argument such as dest='foo' (this uses name 'foo' for the attribute associated to this option).

An option's value is normally a string, but you can include in the call to add_option a named argument such as type='int' (meaning that the value associated with this option must be a decimal representation of an integer and is stored as an int). Acceptable values for named argument type are string, int, long, choice, float, and complex. When you pass type='choice', you must also pass another named argument, choices=..., whose value is a list of strings among which the user must choose one as the value associated with this option (if the user passes this option).

Other useful values of action do not require (nor allow) the user to pass a value associated with the option. 'store_const' stores a constant value in the attribute associated with this option (if the user passes the option at all); when you pass action='store_const', you must also pass another named argument const=..., whose value is the constant to store in the attribute. As a convenience, action can also be 'store_true' or 'store_false', equivalent to 'store_const' with const=True or False, respectively. action='count' increments (by 1 each time the user passes the option) the attribute associated with the option, which is intrinsically an integer with an initial value of 0.

Summarizing, the most frequently used named arguments to add_option are:


action

Action to take when the user passes this option; can be 'store', 'store_const', 'store_true', 'store_false', 'count', or one of several advanced possibilities we did not cover, such as 'callback', 'append', 'help', 'version'.


choices

List of strings allowed as the option's value, when action='store' and type='choice'.


const

Constant to store when the user passes this option, when action='store_const'.


default

Value to store when the user does not pass this option (default is None).


dest

Name of the attribute associated with this option (default is the identifier of the first long-form option string, or the letter of the first short-form option string when there are no long-form option strings).


help

Text to emit to explain this option if the user passes option '-h' or '--help'.


type

Type of the value associated with this option can be 'string', 'int', 'long', 'choice', 'float', or 'complex'.

optparse also allows many highly advanced customization possibilities, including the ability to add other possible actions and types, but I do not cover them in this book.

parse_args

p.parse_args(args=sys.argv[1:])

Parses the list of strings that you pass as args (by default, the command-line arguments of your programs) and returns a pair options,arguments. options is an options-object with attributes set according to your program's available options and the list of arguments that parse_args just parsed; arguments is a (possibly empty) list of the strings that are the non-option-related arguments among those in args.

If parse_args finds any parsing errors (including unknown options, no value associated to an option that needs one, some value associated to an option that does not take one, invalid types, etc.), parse_args writes an error message to sys.stderr and raises SystemExit. If parse_args finds a '-h' or '--help' among the options, it writes a help message to sys.stdout and raises SystemExit.

parse_args also offers possibilities for advanced customization, which I do not cover in this book.

Here is a simple, toy-level example of using optparse. Write the following code into a file named hello.py:

#!/usr/bin/python import optparse

def main( ):
    p = optparse.OptionParser( )
    p.add_option('--verbose', '-v', action='store_true')
    p.add_option('--name', '-n', default="world")
options, arguments = p.parse_args( )
    if options.verbose: print "Greetings and salutations,",
    else: print "Hello",
    print '%s!' % options.name

if _ _name_ _ == '_ _main_ _':
    main( )

The shebang line at the start of the script (as covered in "Running Python Programs" on page 28) helps mostly on Unix-like systems (although it does no harm in Windows), where it must indicate the complete path to your installation of the python interpreter. As also covered in "Running Python Programs" on page 28, you'll probably also want to chmod +x hello.py (again, on Unix-like systems) to make the script directly executable (and, on Windows, you can obtain the same effect if the Python distribution you installed associated the extension .py with the Python interpreter in the Windows Registry, as most distributions do). Now you can run this script at any command-line prompt, and optparse takes care of reading the command-line options you pass, and reacting appropriately to them. For example, a short command-line session on a Unix-like system, with hello.py in the current directory, could go somewhat like the following:

$ ./hello.py
Hello world!
$ ./hello.py --help
usage: hello.py [options]

options:
  -h, --help           show this help message and exit
  -v, --verbose
  -nNAME, --name=NAME
$ ./hello.py -v --name=Alex
Greetings and salutations, Alex!
$ python hello.py -n
usage: hello.py [options]

hello.py: error: -n option requires an argument
$ python hello.py -nthere
Hello there!

The last two examples show that (assuming, of course, that the Python interpreter is in your PATH) you also can run the script by passing it to Python explicitly, with options and arguments for the script placed after the script's filename.



Previous Page
Next Page