Skip to content
Advertisement

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

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement