Python argparse:如何控制子解析器的帮助屏幕中的换行?

时间:2018-10-10 22:25:55

标签: python python-3.6 argparse

我正在使用Python 3.6.3,并具有以下代码:

componentDidMount() {

   this.uploader.on('complete', (id, name, responseJSON, xhr) => {

   const originalName = this.uploader.methods.getName(id);
   const blobName = this.uploader.methods.getBlobName(id);
   const fileSize = this.uploader.methods.getSize(id);

   this.storeFileInfoInDb(originalName, blobName, fileSize);
})
}

帮助输出如下:

import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(prog='foobar',
                                     formatter_class=RawTextHelpFormatter)
parser.add_argument('-lf', '--logfile', dest='logfile', default='/dev/null',
                    help='some very long help message goes here ..............................\n' +
                   'more text here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

subparsers = parser.add_subparsers()
abcd_parser = subparsers.add_parser('abcd')

abcd_parser.add_argument('zzz', nargs='+',
                         help='A very long help message\ngoes here...... more help text goes here zzzzzzz   zzzzzzzzzzzzzzzzzzzzzzz  ')


args = parser.parse_args()

上面的输出没有按预期包装帮助文本(除非我明确放在“ \ n”中)

但是,子解析器的帮助输出如下:

$ ./foobar  -h
usage: foobar [-h] [-lf LOGFILE] {abcd} ...

positional arguments:
  {abcd}

optional arguments:
  -h, --help            show this help message and exit
  -lf LOGFILE, --logfile LOGFILE
                        some very long help message goes here ..............................
                        more text here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  1. 我如何才能将“转到此处”打印在新行上(我指定为“ \ n”,但这行不通)
  2. 如何禁用换行符,以使“ zzz”参数的整个帮助文本都在一行上?

1 个答案:

答案 0 :(得分:0)

您需要为子解析器提供与主解析器相同的formatter_class,您可以通过将formatter_class传递给add_parser来做到这一点:

abcd_parser = subparsers.add_parser('abcd', formatter_class=RawTextHelpFormatter)