I'm using python's argparse to handle parsing of arguments. I get a default help message structured like so:
usage: ProgramName [-h] ...
Description
positional arguments:
...
optional arguments:
-h, --help show this help message and exit
...
What I want is to add an entire new section to this message, for example:
usage: ProgramName [-h] ...
Description
positional arguments:
...
optional arguments:
-h, --help show this help message and exit
...
additional information:
This will show additional information relevant to the user.
....
Is there a way to achieve this behavior? A solution that is supported by both python 2.7 and 3.x is preferred.
Edit: I would also rather have a solution that will add the new section / sections at the bottom of the help message.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.
You can quite do it using epilog. Here is an example below:
import argparse
import textwrap
parser = argparse.ArgumentParser(
prog='ProgramName',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''\
additional information:
I have indented it
exactly the way
I want it
'''))
parser.add_argument('--foo', nargs='?', help='foo help')
parser.add_argument('bar', nargs='+', help='bar help')
parser.print_help()
Result :
usage: ProgramName [-h] [--foo [FOO]] bar [bar ...]
positional arguments:
bar bar help
optional arguments:
-h, --help show this help message and exit
--foo [FOO] foo help
additional information:
I have indented it
exactly the way
I want it
There are multiple ways in which you can add a description to your command. The recommended way is to add a module documentation at the top of your source code file as in:
""" This is the description, it will be accessible within the variable
__doc__
"""
And then:
parser = argparse.ArgumentParser(description=__doc__)
To add text below the parameter description, use epilog, as shown in the following example taken from the documentation:
>>> parser = argparse.ArgumentParser(description='A foo that bars',
epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]
A foo that bars
optional arguments: -h, --help show this help message and exit
And that's how you'd foo a bar
Refer to the documentation (linked above) for more information.
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