如何在 argparse 帮助文本中插入换行符? [英] How to insert newlines on argparse help text?

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

问题描述

我在 Python 2.7 中使用 argparse解析输入选项.我的选择之一是多项选择.我想在其帮助文本中列出一个列表,例如

from argparse import ArgumentParserparser = ArgumentParser(description='test')parser.add_argument('-g', selection=['a', 'b', 'g', 'd', 'e'], default='a',help="一些选项,其中\n"" a = alpha\n"" b = 测试版\n"" g = 伽马\n"" d = delta\n"" e = epsilon")parser.parse_args()

然而,argparse 会去除所有换行符和连续空格.结果看起来像

<前>~/下载:52$ python2.7 x.py -h用法:x.py [-h] [-g {a,b,g,d,e}]测试可选参数:-h, --help 显示此帮助信息并退出-g {a,b,g,d,e} 一些选项,其中 a = alpha b = beta g = gamma d = delta e= 厄普西隆

如何在帮助文本中插入换行符?

解决方案

尝试使用 RawTextHelpFormatter:

from argparse import RawTextHelpFormatterparser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.

from argparse import ArgumentParser

parser = ArgumentParser(description='test')

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
    help="Some option, where\n"
         " a = alpha\n"
         " b = beta\n"
         " g = gamma\n"
         " d = delta\n"
         " e = epsilon")

parser.parse_args()

However, argparse strips all newlines and consecutive spaces. The result looks like

~/Downloads:52$ python2.7 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]

test

optional arguments:
  -h, --help      show this help message and exit
  -g {a,b,g,d,e}  Some option, where a = alpha b = beta g = gamma d = delta e
                  = epsilon

How to insert newlines in the help text?

解决方案

Try using RawTextHelpFormatter:

from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

这篇关于如何在 argparse 帮助文本中插入换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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