Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?
-
See this SO: http://stackoverflow.com/questions/12151306/argparse-way-to-include-default-values-in-help – Mingjiang Shi Jan 16 '14 at 09:26
-
If somebody seeks the same for Argparse: [Argparse: Way to include default values in '--help'?](http://stackoverflow.com/a/12151325/562769) – Martin Thoma Feb 24 '14 at 07:48
5 Answers
Try using the %default
string placeholder:
# This example taken from http://docs.python.org/library/optparse.html#generating-help
parser.add_option("-m", "--mode",
default="intermediate",
help="interaction mode: novice, intermediate, "
"or expert [default: %default]")

- 95,172
- 10
- 132
- 126
And if you want to add default values automatically to all options that you have specified, you can do the following:
for option in parser.option_list:
if option.default != ("NO", "DEFAULT"):
option.help += (" " if option.help else "") + "[default: %default]"

- 121
- 1
- 3
And if you need programmatic access to the default values, you can get to them via the defaults
attribute of the parser (it's a dict)

- 297,451
- 125
- 333
- 465

- 14,305
- 8
- 42
- 46
The comments to your question already indicate there's another way to parse arguments called argparse. It's been introduced in Python 3.2. It actually deprecates optparse
but is used similarly.
argpass
comes with different formatting classes and for instance argparse.ArgumentDefaultsHelpFormatter
will also print the default values without you having to manipulate the help string manually.
ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:
class argparse.RawDescriptionHelpFormatter
class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter
class argparse.MetavarTypeHelpFormatter
An example from the python docs:
>>> parser = argparse.ArgumentParser(
... prog='PROG',
... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar [bar ...]]
positional arguments:
bar BAR! (default: [1, 2, 3])
optional arguments:
-h, --help show this help message and exit
--foo FOO FOO! (default: 42)

- 8,189
- 1
- 49
- 64
Add argparse.ArgumentDefaultsHelpFormatter to your parser
import argparse
parser = argparse.ArgumentParser(
description='Your application description',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
from documentation:
ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages: Blockquote

- 83,883
- 25
- 248
- 179