Display pydoc's description as part of argparse '--help'
You can retrieve the docstring of your script from the __doc__
global. To add it to your script's help, you can set the description
argument of the parser.
"""My python scriptScript to process a file"""p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)p.add_argument('foo', help="Name of file to process")p.parse_args()
Then the help will look like:
$ python tmp.py --helpusage: tmp.py [-h] fooMy python scriptScript to process a filepositional arguments: foo Name of file to processoptional arguments: -h, --help show this help message and exit
You can use the epilog
keyword argument instead of description
to move the docstring to the end of the help, instead of immediately following the usage string.
There is an elegant argparse wrapper allowing to use a Python function docstring as a command help in your command line interface: dsargparse
It does this smartly keeping only the description part of the function docstring not the arguments part that can be irrelevant to your command.
As mentioned in its Readme:
dsargparse is a wrapper of argparse library which prepares helps and descriptions from docstrings. It also sets up functions to be run for each sub command, and provides a helper function which parses args and run a selected command. Using this library, you don't need to write same texts in docstrings, help, and description.