6.20.3.2 Defining options

Each Option instance represents a set of synonymous command-line options, i.e. options that have the same meaning and effect, but different spellings. You can specify any number of short or long option strings, but you must specify at least one option string.

To define an option with only a short option string:

make_option("-f", ...)

And to define an option with only a long option string:

make_option("--foo", ...)

The ``...'' represents a set of keyword arguments that define attributes of the Option object. The rules governing which keyword args you must supply for a given Option are fairly complicated, but you always have to supply some. If you get it wrong, optparse raises an OptionError exception explaining your mistake.

The most important attribute of an option is its action, i.e. what to do when we encounter this option on the command-line. The possible actions are:

Action  Meaning 
store store this option's argument (default)
store_const store a constant value
store_true store a true value
store_false store a false value
append append this option's argument to a list
count increment a counter by one
callback call a specified function
help print a usage message including all options and the documentation for them

(If you don't supply an action, the default is ``store''. For this action, you may also supply type and dest keywords; see below.)

As you can see, most actions involve storing or updating a value somewhere. optparse always creates a particular object (an instance of the Values class) specifically for this purpose. Option arguments (and various other values) are stored as attributes of this object, according to the dest (destination) argument to make_option()/add_option().

For example, when you call:

parser.parse_args()

one of the first things optparse does is create a values object:

values = Values()

If one of the options in this parser is defined with:

make_option("-f", "--file", action="store", type="string", dest="filename")

and the command-line being parsed includes any of the following:

-ffoo
-f foo
--file=foo
--file foo

then optparse, on seeing the -f or --file option, will do the equivalent of this:

  values.filename = "foo"

Clearly, the type and dest arguments are almost as important as action. action is the only attribute that is meaningful for all options, though, so it is the most important.

See About this document... for information on suggesting changes.