Can Python's optparse display the default value of an option?

Question:

Is there a way to make Python’s optparse print the default value of an option or flag when showing the help with –help?

Asked By: pupeno

||

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]")
Answered By: Jarret Hardie

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)

Answered By: Arkady

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]"
Answered By: Andrey Petrov

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)

see argparse formatting classes

Answered By: DomTomCat

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

Answered By: Vlad Bezden
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.