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:
And to define an option with only a long option string:
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:
||store this option's argument (default)|
||store a constant value|
||store a true value|
||store a false value|
||append this option's argument to a list|
||increment a counter by one|
||call a specified function|
||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:
one of the first things optparse does is create a
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.