Suppose I have the following argparse snippet:
diags.cmdln_parser.add_argument( '--scan-time', action = 'store', nargs = '?', type = int, default = 5, help = "Wait SCAN-TIME seconds between status checks.")
Currently, --help
returns:
usage: connection_check.py [-h] [--version] [--scan-time [SCAN_TIME]] Test the reliability/uptime of a connection. optional arguments: -h, --help show this help message and exit --version show program's version number and exit --scan-time [SCAN_TIME] Wait SCAN-TIME seconds between status checks.
I would prefer something like:
--scan-time [SCAN_TIME] Wait SCAN-TIME seconds between status checks. (Default = 5)
Peeking at the help formatter code revealed limited options. Is there a clever way to get argparse
to print the default value for --scan-time
in a similar fashion, or should I just subclass the help
formatter?
The argparse module will automatically allow an option -h or --help that prints a usage string for all the registered options. By default, the type is str , the default value is None , the help string is empty, and metavar is the option in upper case without initial dashes.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
Use the argparse.ArgumentDefaultsHelpFormatter
formatter:
parser = argparse.ArgumentParser( # ... other options ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
To quote the documentation:
The other formatter class available,
ArgumentDefaultsHelpFormatter
, will add information about the default value of each of the arguments.
Note that this only applies to arguments that have help text defined; with no help
value for an argument, there is no help message to add information about the default value to.
The exact output for your scan-time option then becomes:
--scan-time [SCAN_TIME] Wait SCAN-TIME seconds between status checks. (default: 5)
Add '%(default)s'
to the help parameter to control what is displayed.
parser.add_argument("--type", default="toto", choices=["toto","titi"], help = "type (default: %(default)s)")
Notes:
%
+ default in parenthesis + format characters (not to be confused with curly brackets {default}
we find in format
or f-string)s
for strings, d
for integers, f
for floats, etc.)You can refer to printf documentation for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With