Python argparse:如何在子解析器中插入换行符帮助文本? [英] Python argparse: How to insert newline the help text in subparser?
问题描述
此问题与之前提出的问题有关,但可能无关.问题是:当使用子解析器时,如何在下面给定(工作)示例中的帮助文本中使用换行符?
导入 argparse解析器 = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)subparsers = parser.add_subparsers()parser_start = subparsers.add_parser('停止')parser_start.add_argument("file", help = "firstline\nnext line\nlast line")打印 parser.parse_args()
我的输出如下:
tester.py stop -h用法:tester.py 停止 [-h] 文件位置参数:文件第一行下一行最后一行可选参数:-h, --help 显示此帮助信息并退出
file
帮助的预期输出应该是:
第一行下一行最后一行
subparsers.add_parser()
方法采用与 argparse 相同的
.因此,要将 ArgumentParser
构造函数参数.ArgumentParser()RawTextHelpFormatter
用于子解析器,您需要在添加子解析器时显式设置 formatter_class
.
更改此行以设置子解析器的formatter_class
:
现在,您的帮助文本将包含换行符:
<预><代码>>>>parser_start.add_argument("file", help="第一行\n下一行\n最后一行")_StoreAction(option_strings=[], dest='file', nargs=None, const=None, default=None, type=None, selection=None, help='firstline\nnext line\nlast line', metavar=None)>>>打印 parser.parse_args(['stop', '--help'])用法:停止[-h]文件位置参数:文件第一行下一行最后一行可选参数:-h, --help 显示此帮助信息并退出This question is related to a question asked earlier, but might be unrelated. Question is: How to use newlines in the help text in the given (working) example below, when using 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()
My output is as follows:
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
The expected output for the help on file
should be:
first line
next line
last line
The subparsers.add_parser()
method takes the same ArgumentParser
constructor arguments as argparse.ArgumentParser()
. So, to use the RawTextHelpFormatter
for the subparser, you need to set the formatter_class
explicitly when you add the subparser.
>>> import argparse
>>> parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
>>> subparsers = parser.add_subparsers()
Change this line to set the formatter_class
of the subparser:
>>> parser_start = subparsers.add_parser('stop', formatter_class=argparse.RawTextHelpFormatter)
Now, your help text will contain the newlines:
>>> 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
这篇关于Python argparse:如何在子解析器中插入换行符帮助文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!