Python Library Reference
Previous: Up: 14.3.2 Tutorial Next:


14.3.2.6 Generating help

optparse's ability to generate help and usage text automatically is useful for creating user-friendly command-line interfaces. All you have to do is supply a help value for each option, and optionally a short usage message for your whole program. Here's an OptionParser populated with user-friendly (documented) options:

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
 action="store_true", dest="verbose", default=True,
 help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
 action="store_false", dest="verbose", 
 help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
 metavar="FILE", help="write output to FILE"),
parser.add_option("-m", "--mode",
 default="intermediate",
 help="interaction mode: novice, intermediate, "
 "or expert [default: %default]")

If optparse encounters either -h or --help on the command-line, or if you just call parser.print_help(), it prints the following to standard output:

usage: <yourscript> [options] arg1 arg2
options:
 -h, --help show this help message and exit
 -v, --verbose make lots of noise [default]
 -q, --quiet be vewwy quiet (I'm hunting wabbits)
 -f FILE, --filename=FILE
 write output to FILE
 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
 expert [default: intermediate]

(If the help output is triggered by a help option, optparse exits after printing the help text.)

There's a lot going on here to help optparse generate the best possible help message:

When dealing with many options, it is convenient to group these options for better help output. An OptionParser can contain several option groups, each of which can contain several options.

Continuing with the parser defined above, adding an OptionGroup to a parser is easy:

group = OptionGroup(parser, ``Dangerous Options'',
 ``Caution: use these options at your own risk. ``
 ``It is believed that some of them bite.'')
group.add_option(``-g'', action=''store_true'', help=''Group option.'')
parser.add_option_group(group)

This would result in the following help output:

usage: [options] arg1 arg2
options:
 -h, --help show this help message and exit
 -v, --verbose make lots of noise [default]
 -q, --quiet be vewwy quiet (I'm hunting wabbits)
 -fFILE, --file=FILE write output to FILE
 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
 [default], 'expert'
 Dangerous Options:
 Caution: use of these options is at your own risk. It is believed that
 some of them bite.
 -g Group option.


Python Library Reference
Previous: Up: 14.3.2 Tutorial Next:

Release 2.5.2, documentation updated on 21st February, 2008.
See About this document... for information on suggesting changes.

AltStyle によって変換されたページ (->オリジナル) /