【问题标题】:Python argparse: How to insert newline the help text in subparser?Python argparse:如何在 subparser 中插入换行符帮助文本?
【发布时间】:2013-03-09 23:05:40
【问题描述】:

此问题与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

【问题讨论】:

    标签: python python-2.7 argparse


    【解决方案1】:

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

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

    更改此行以设置子解析器的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
    

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 2016-05-29
      • 2015-06-11
      • 2020-10-12
      • 1970-01-01
      • 2018-06-24
      • 2015-07-30
      • 2015-06-19
      相关资源
      最近更新 更多