Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display pydoc's description as part of argparse '--help'

Tags:

I am using argparse.ArgumentParser() in my script, I would like to display the pydoc description of my script as part of the '--help' option of the argparse.

One possibly solution can be to use the formatter_class or the description attribute of ArgumentParser to configure the displaying of help. But in this case, we need to use the 'pydoc' command internally to fetch the description.

Do we have some other ways (possibly elegant) to do it?

like image 890
baky Avatar asked Aug 07 '13 14:08

baky


People also ask

How do I get help from Argparse?

Showing a Brief Description of What an Argument Does A great feature of the Python argparse library is that, by default, you have the ability to ask for help just by adding the -h flag to your command line.

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.


1 Answers

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 script  Script 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 --help usage: tmp.py [-h] foo  My python script  Script to process a file  positional arguments:   foo         Name of file to process  optional 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.

like image 197
chepner Avatar answered Oct 11 '22 02:10

chepner