41

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.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Yoavhayun
  • 499
  • 1
  • 8
  • 16

2 Answers2

60

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
Jundiaius
  • 6,214
  • 3
  • 30
  • 43
dbaxime
  • 716
  • 5
  • 3
25

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.

Daniel
  • 11,332
  • 9
  • 44
  • 72