我有以下脚本:
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()
打印(TEST_DESCRIPTION)
如果没有任何选项,则输出如我所期望的(带有适当的换行和缩进)
# ./test2.py
This script issues the following commands:
1. Command1
2. Command2
3. Command3
然而,当我使用"-h"选项时,当TEST_DESCRIPTION传递给argparse.ArgumentParser()时,似乎从TEST_DESCRIPTION中删除了换行符和缩进。
# ./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
无论如何,我可以保留TEST_DESCRIPTION的格式,因为它是在传递给argparse.ArgumentParser()时编写的。(我试着让它成为一个原始字符串,插入n,但没有运气。)
你需要RawTextHelpFormatter
,它就在文档中:
parser = argparse.ArgumentParser(description=TEST_DESCRIPTION,
formatter_class=argparse.RawTextHelpFormatter)