Ale*_*lex 10 python python-2.7 argparse
这个问题与之前提出的问题有关,但可能不相关.问题是:在使用subparsers时,如何在下面给定(工作)示例的帮助文本中使用换行符?
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()
Run Code Online (Sandbox Code Playgroud)
我的输出如下:
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
Run Code Online (Sandbox Code Playgroud)
帮助的预期输出file应该是:
first line
next line
last line
Run Code Online (Sandbox Code Playgroud)
Tom*_*ann 10
该subparsers.add_parser()方法采用与ArgumentParser构造函数相同的参数argparse.ArgumentParser().因此,要使用RawTextHelpFormattersubparser,您需要formatter_class在添加subparser时明确设置.
>>> import argparse
>>> parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
>>> subparsers = parser.add_subparsers()
Run Code Online (Sandbox Code Playgroud)
更改此行以设置formatter_classsubparser:
>>> parser_start = subparsers.add_parser('stop', formatter_class=argparse.RawTextHelpFormatter)
Run Code Online (Sandbox Code Playgroud)
现在,您的帮助文本将包含换行符:
>>> 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4667 次 |
| 最近记录: |