Search code examples
pythonpython-3.xargparse

Description parameter to argparse.ArgumentParser() function


I have the following script:

import argparse

TEST_DESCRIPTION = """
This script issues the following commands:
    1. Command1
    2. Command2
    3. Command3
"""

parser = argparse.ArgumentParser(description=TEST_DESCRIPTION)
args = parser.parse_args()

print(TEST_DESCRIPTION)

Without any option, the output is as I expected (with proper newlines and indentation)

# ./test2.py

This script issues the following commands:
    1. Command1
    2. Command2
    3. Command3

However, when I use the "-h" option, it seems the newlines and indentations are removed from TEST_DESCRIPTION when it is passed to argparse.ArgumentParser().

# ./test2.py -h
usage: test2.py [-h]

This script issues the following commands: 1. Command1 2. Command2 3. Command3

optional arguments:
  -h, --help  show this help message and exit

Is there anyway I can preserve the formatting of TEST_DESCRIPTION as it is written when it is passed to argparse.ArgumentParser(). (I tried making it a raw string, inserting \n, but no luck.)


Solution

  • You need RawTextHelpFormatter, it's right there in the docs:

    parser = argparse.ArgumentParser(description=TEST_DESCRIPTION, 
                                     formatter_class=argparse.RawTextHelpFormatter)