I’m using python’s argparse to handle parsing of arguments. I get a default help message structured like so:
JavaScript
x
11
11
1
usage: ProgramName [-h]
2
3
Description
4
5
positional arguments:
6
7
8
optional arguments:
9
-h, --help show this help message and exit
10
11
What I want is to add an entire new section to this message, for example:
JavaScript
1
15
15
1
usage: ProgramName [-h]
2
3
Description
4
5
positional arguments:
6
7
8
optional arguments:
9
-h, --help show this help message and exit
10
11
12
additional information:
13
This will show additional information relevant to the user.
14
.
15
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:
JavaScript
1
15
15
1
import argparse
2
import textwrap
3
parser = argparse.ArgumentParser(
4
prog='ProgramName',
5
formatter_class=argparse.RawDescriptionHelpFormatter,
6
epilog=textwrap.dedent('''
7
additional information:
8
I have indented it
9
exactly the way
10
I want it
11
'''))
12
parser.add_argument('--foo', nargs='?', help='foo help')
13
parser.add_argument('bar', nargs='+', help='bar help')
14
parser.print_help()
15
Result :
JavaScript
1
14
14
1
usage: ProgramName [-h] [--foo [FOO]] bar [bar ]
2
3
positional arguments:
4
bar bar help
5
6
optional arguments:
7
-h, --help show this help message and exit
8
--foo [FOO] foo help
9
10
additional information:
11
I have indented it
12
exactly the way
13
I want it
14