54
Python Module of the Week, Release 1.132
Organizing Options
Many applications include sets ofrelatedoptions. For example, rpm includes separate options foreach ofits operating
modes.optparse uses option groups to organize options in the help output. The option values are all still saved in
asingle Values instance, so the namespace for option names is still flat.
import optparse
parser = optparse.OptionParser()
parser.add_option(’-q’, action=’store_const’, const=’query’, dest=’mode’,
help=’Query’)
parser.add_option(’-i’, action=’store_const’, const=’install’, dest=’mode’,
help=’Install’)
query_opts = optparse.OptionGroup(
parser, ’Query Options’,
’These options control the query mode.’,
)
query_opts.add_option(’-l’, action=’store_const’, const=’list’, dest=’query_mode’,
help=’List contents’)
query_opts.add_option(’-f’, action=’store_const’, const=’file’, dest=’query_mode’,
help=’Show owner of f file’)
query_opts.add_option(’-a’, action=’store_const’, const=’all’, dest=’query_mode’,
help=’Show all l packages’)
parser.add_option_group(query_opts)
install_opts = optparse.OptionGroup(
parser, ’Installation Options’,
’These options control installation.’,
)
install_opts.add_option(’--hash’, action=’store_true’, default=False,
help=’Show hash marks as progress indication’)
install_opts.add_option(’--force’, dest=’install_force’, action=’store_true’, default=False,
help=’Install, regardless of f depdencies or r existing g version’)
parser.add_option_group(install_opts)
print parser.parse_args()
Each group has its own section title and description, and the options are displayed together.
$ python optparse_groups.py -h
Usage: optparse_groups.py [options]
Options:
-h, --help
show this help message and exit
-q
Query
-i
Install
Query Options:
These options control the query mode.
-l
List contents
-f
Show owner of file
-a
Show all packages
Installation Options:
These options control installation.
412
Chapter 15. Generic Operating System Services