Python argparse:如何在subparser中插入换行帮助文本?

时间:2013-03-20 17:26:22

标签: python python-2.7 argparse

此问题与question asked earlier有关,但可能不相关。问题是:在使用子分析符时,如何在下面给定(工作)示例的帮助文本中使用换行符?

import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)

subparsers = parser.add_subparsers()

parser_start = subparsers.add_parser('stop')
parser_start.add_argument("file", help = "firstline\nnext line\nlast line")

print parser.parse_args()

我的输出如下:

tester.py  stop -h
usage: tester.py stop [-h] file

positional arguments:
  file        firstline next line last line

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

file上的帮助的预期输出应为:

first line
next line
last line

1 个答案:

答案 0 :(得分:10)

subparsers.add_parser()方法采用与ArgumentParser相同的argparse.ArgumentParser()构造函数参数。因此,要将RawTextHelpFormatter用于subparser,您需要在添加subparser时明确设置formatter_class

>>> import argparse
>>> parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
>>> subparsers = parser.add_subparsers()

更改此行以设置subparser的formatter_class

>>> parser_start = subparsers.add_parser('stop', formatter_class=argparse.RawTextHelpFormatter)

现在,您的帮助文字将包含换行符:

>>> parser_start.add_argument("file", help="firstline\nnext line\nlast line")
_StoreAction(option_strings=[], dest='file', nargs=None, const=None, default=None, type=None, choices=None, help='firstline\nnext line\nlast line', metavar=None)

>>> print parser.parse_args(['stop', '--help'])
usage:  stop [-h] file

positional arguments:
  file        firstline
              next line
              last line

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