6.20.2.1 The store action

The action tells optparse what to do when it sees one of the option strings for this option on the command-line. For example, the action store means: take the next argument (or the remainder of the current argument), ensure that it is of the correct type, and store it to your chosen destination.

For example, let's fill in the ``...'' of that last option:

parser.add_option("-f", "--file",
                  action="store", type="string", dest="filename")

Now let's make up a fake command-line and ask optparse to parse it:

args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)

(Note that if you don't pass an argument list to parse_args(), it automatically uses sys.argv[1:].)

When optparse sees the -f, it consumes the next argument--foo.txt--and stores it in the filename attribute of a special object. That object is the first return value from parse_args(), so:

print options.filename

will print foo.txt.

Other option types supported by optparse are int and float. Here's an option that expects an integer argument:

parser.add_option("-n", type="int", dest="num")

This example doesn't provide a long option, which is perfectly acceptable. It also doesn't specify the action--it defaults to ``store''.

Let's parse another fake command-line. This time, we'll jam the option argument right up against the option, since -n42 (one argument) is equivalent to -n 42 (two arguments).

(options, args) = parser.parse_args(["-n42"])
print options.num

This prints 42.

Trying out the ``float'' type is left as an exercise for the reader.

If you don't specify a type, optparse assumes ``string''. Combined with the fact that the default action is ``store'', that means our first example can be a lot shorter:

parser.add_option("-f", "--file", dest="filename")

If you don't supply a destination, optparse figures out a sensible default from the option strings: if the first long option string is --foo-bar, then the default destination is foo_bar. If there are no long option strings, optparse looks at the first short option: the default destination for -f is f.

Adding types is fairly easy; please refer to section 6.20.5, ``Adding new types.''

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