Python argparse: How to insert newline the help text in subparser?

断了今生、忘了曾经 提交于 2019-12-10 02:47:05

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/15530575/python-argparse-how-to-insert-newline-the-help-text-in-subparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!