Pablo Fernandez
Pablo Fernandez

Reputation: 287500

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

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

Upvotes: 43

Views: 4861

Answers (5)

Vlad Bezden
Vlad Bezden

Reputation: 89617

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

Upvotes: 0

DomTomCat
DomTomCat

Reputation: 8569

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

Upvotes: 0

Andrey Petrov
Andrey Petrov

Reputation: 121

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]"

Upvotes: 8

Arkady
Arkady

Reputation: 15069

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)

Upvotes: 7

Jarret Hardie
Jarret Hardie

Reputation: 97962

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]")

Upvotes: 55

Related Questions