自定义argparse帮助消息 [英] Customize argparse help message

查看:48
本文介绍了自定义argparse帮助消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下示例代码来演示我的问题.

I have written the following sample code to demonstrate my issue.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', action='version',
                    version='%(prog)s 1.0')
parser.parse_args()

这会产生以下帮助消息.

This produces the following help message.

$ python foo.py --help
usage: foo.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --version  show program's version number and exit

我想自定义此帮助输出,以便将所有短语和句子都大写,并在句号后面加句号.换句话说,我希望这样生成帮助消息.

I want to customize this help output such that it capitalizes all phrases and sentences, and puts period after sentences. In other words, I want the help message to be generated like this.

$ python foo.py --help
Usage: foo.py [-h] [-v]

Optional arguments:
  -h, --help     Show this help message and exit.
  -v, --version  Show program's version number and exit.

这是我可以使用argparse API进行控制的东西.如果是这样,怎么办?您能否提供一个小例子来说明如何做到这一点?

Is this something that I can control using the argparse API. If so, how? Could you please provide a small example that shows how this can be done?

推荐答案

首先:大写这些短语在约定俗成的情况下是行不通的,argparse并不是真正帮助您轻松更改这些字符串的工具.您在这里有三种不同的字符串类:帮助格式化程序的样板文本,节标题和每个特定选项的帮助文本.所有这些字符串都可以本地化;您可以通过稍微阅读一下源代码.

First of all: capitalising those phrases flies in the face of convention, and argparse isn't really tooled to help you change these strings easily. You have three different classes of strings here: boilerplate text from the help formatter, section titles, and help text per specific option. All these strings are localisable; you could just provide a 'capitalised' translation for all of these strings via the gettext() module support. That said, you can reach in and replace all these strings if you are determined enough and read the source code a little.

version操作包括默认的help文本,但是您可以通过设置help参数来提供自己的文本. help动作也是如此;如果您将 add_help参数设置为False可以手动添加该操作:

The version action includes a default help text, but you can supply your own by setting the help argument. The same applies to the help action; if you set the add_help argument to False you can add that action manually:

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-v', '--version', action='version',
                    version='%(prog)s 1.0', help="Show program's version number and exit.")
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
                    help='Show this help message and exit.')

接下来,optional arguments消息是组标题;每个解析器都有两个默认组,一个用于位置参数,另一个用于可选.您可以通过属性_positionals_optionals来达到这些目的,这两个属性均具有title属性:

Next, the optional arguments message is a group title; each parser has two default groups, one for positional arguments, the other for optional. You can reach these by the attributes _positionals and _optionals, both of which have a title attribute:

parser._positionals.title = 'Positional arguments'
parser._optionals.title = 'Optional arguments'

被警告,通过访问以下划线开头的名称,您正在尝试使用该模块未公开的私有API,并且您的代码可能会在以后的更新中中断.

Be warned, by accessing names starting with an underscore you are venturing into the undocumented private API of the module, and your code may break in future updates.

最后,要更改usage字符串,您必须将帮助格式化程序子类化.将子类作为 formatter_class参数:

Finally, to change the usage string, you'll have to subclass the help formatter; pass the subclass in as the formatter_class argument:

class CapitalisedHelpFormatter(argparse.HelpFormatter):
    def add_usage(self, usage, actions, groups, prefix=None):
        if prefix is None:
            prefix = 'Usage: '
        return super(CapitalisedHelpFormatter, self).add_usage(
            usage, actions, groups, prefix)

parser = argparse.ArgumentParser(formatter_class=CapitalisedHelpFormatter)

演示,将所有这些放在一起:

Demo, putting these all together:

>>> import argparse
>>> class CapitalisedHelpFormatter(argparse.HelpFormatter):
...     def add_usage(self, usage, actions, groups, prefix=None):
...         if prefix is None:
...             prefix = 'Usage: '
...         return super(CapitalisedHelpFormatter, self).add_usage(
...             usage, actions, groups, prefix)
...
>>> parser = argparse.ArgumentParser(add_help=False, formatter_class=CapitalisedHelpFormatter)
>>> parser._positionals.title = 'Positional arguments'
>>> parser._optionals.title = 'Optional arguments'
>>> parser.add_argument('-v', '--version', action='version',
...                     version='%(prog)s 1.0', help="Show program's version number and exit.")
_VersionAction(option_strings=['-v', '--version'], dest='version', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help="Show program's version number and exit.", metavar=None)
>>> parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
...                     help='Show this help message and exit.')
_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='Show this help message and exit.', metavar=None)
>>> print(parser.format_help())
Usage: [-v] [-h]

Optional arguments:
  -v, --version  Show program's version number and exit.
  -h, --help     Show this help message and exit.

这篇关于自定义argparse帮助消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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