Python argparse:如何在子解析器中插入换行符帮助文本? [英] Python argparse: How to insert newline the help text in subparser?

查看:120
本文介绍了Python argparse:如何在子解析器中插入换行符帮助文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题与之前提出的问题有关a>,但可能无关.问题是:在使用子解析器时,如何在下面给定的(有效)示例中的帮助文本中使用换行符?

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()

我的输出如下:

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上的帮助的预期输出应为:

The expected output for the help on file should be:

first line
next line
last line

推荐答案

subparsers.add_parser()方法采用与argparse.ArgumentParser()相同的ArgumentParser构造函数参数.因此,要将RawTextHelpFormatter用于子解析器,则需要在添加子解析器时显式设置formatter_class.

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()

更改此行以设置子解析器的formatter_class:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆