Python Argparse - How can I add text to the default help message? Python Argparse - How can I add text to the default help message? python-3.x python-3.x

Python Argparse - How can I add text to the default help message?


You can quite do it using epilog.Here is an example below:

import argparseimport textwrapparser = 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 helpoptional arguments:  -h, --help   show this help message and exit  --foo [FOO]  foo helpadditional 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 barsoptional arguments:  -h, --help  show this help message and exitAnd that's how you'd foo a bar

Refer to the documentation (linked above) for more information.