【问题标题】:Description parameter to argparse.ArgumentParser() functionargparse.ArgumentParser() 函数的描述参数
【发布时间】:2013-03-25 14:36:22
【问题描述】:

我有以下脚本:

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”选项时,似乎换行符和缩进在传递给 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,但没有运气。)

【问题讨论】:

    标签: python python-3.x argparse


    【解决方案1】:

    你需要RawTextHelpFormatter,它是right there in the docs

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

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 2021-05-06
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多