Can Python optparse display the default value for a parameter?

Is there a way to make Python optparse print the default value for a parameter or flag when showing help with -help?

+41
python optparse
Aug 10 '09 at 11:55
source share
5 answers

Try using the %default 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]") 
+54
Aug 10 '09 at 12:01
source share

And if you need programmatic access to the default values, you can get to them using the analyzer defaults attribute (it a dict)

+7
Aug 10 '09 at 12:04
source share

And if you want to automatically add default values ​​to all the options you specify, you can do the following:

 for option in parser.option_list: if option.default != ("NO", "DEFAULT"): option.help += (" " if option.help else "") + "[default: %default]" 
+7
Aug 10 2018-12-12T00:
source share

The comments on your question already point to another way of parsing argparse arguments. It was introduced in Python 3.2. It actually depreciates optparse , but is used similarly.

argpass comes with various formatting classes and, for example, argparse.ArgumentDefaultsHelpFormatter also prints the default values ​​without using the help line manually.

ArgumentParser objects let you customize help formatting by specifying an alternative formatting class. There are currently four such classes:

class argparse.RawDescriptionHelpFormatter

class argparse.RawTextHelpFormatter

class argparse.ArgumentDefaultsHelpFormatter

class argparse.MetavarTypeHelpFormatter

An example from 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

0
Nov 28 '15 at 8:07
source share

Add argparse.ArgumentDefaultsHelpFormatter to your parser

  import argparse parser = argparse.ArgumentParser( description='Your application description', formatter_class=argparse.ArgumentDefaultsHelpFormatter) 

from the documentation:

ArgumentDefaultsHelpFormatter automatically adds default information for each of the arguments: Blockquote

0
Jan 12 '17 at 15:53 ​​on
source share



All Articles