6.20.2.4 Generating help

The last feature that you will use in every script is optparse's ability to generate help messages. All you have to do is supply a help argument when you add an option. Let's create a new parser and populate it 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", "--file", dest="filename",
                  metavar="FILE", help="write output to FILE"),
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: one of 'novice', "
                       "'intermediate' [default], 'expert'")

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

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)
  -fFILE, --file=FILE  write output to FILE
  -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
                       [default], 'expert'

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.

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