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

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

问题描述

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

导入 argparse解析器 = argparse.ArgumentParser()parser.add_argument('-v', '--version', action='version',version='%(prog)s 1.0')parser.parse_args()

这会产生以下帮助消息.

$ python foo.py --help用法:foo.py [-h] [-v]可选参数:-h, --help 显示此帮助信息并退出-v, --version 显示程序的版本号并退出

我想自定义此帮助输出,使其大写所有短语和句子,并在句子后放置句号.换句话说,我希望帮助消息像这样生成.

$ python foo.py --help用法:foo.py [-h] [-v]可选参数:-h, --help 显示此帮助信息并退出.-v, --version 显示程序的版本号并退出.

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

解决方案

首先:大写这些短语与惯例背道而驰,并且 argparse 并没有真正帮助您改变这些字符串容易.这里有三类不同的字符串:来自帮助格式化程序的样板文本、章节标题和每个特定选项的帮助文本.所有这些字符串都是可本地化的;您可以通过gettext() 模块支持.也就是说,如果您有足够的决心并且 稍微阅读源代码.

version 操作包括默认的 help 文本,但您可以通过设置 help 参数来提供您自己的文本.这同样适用于 help 动作;如果您设置了 add_help 参数False,您可以手动添加该操作:

parser = argparse.ArgumentParser(add_help=False)parser.add_argument('-v', '--version', action='version',version='%(prog)s 1.0', help="显示程序的版本号并退出.")parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,help='显示此帮助消息并退出.')

接下来,可选参数消息是一个组标题;每个解析器都有两个默认组,一个用于位置参数,另一个用于可选.您可以通过属性 _positionals_optionals 来访问它们,这两个属性都有一个 title 属性:

parser._positionals.title = '位置参数'parser._optionals.title = '可选参数'

请注意,通过访问以下划线开头的名称,您正在冒险进入模块的未记录的私有 API,并且您的代码可能会在未来的更新中崩溃.

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

class CapitalisedHelpFormatter(argparse.HelpFormatter):def add_usage(自我,用法,动作,组,前缀=无):如果前缀为无:前缀 = '用法:'返回 super(CapitalisedHelpFormatter, self).add_usage(用法、动作、组、前缀)解析器 = argparse.ArgumentParser(formatter_class=CapitalisedHelpFormatter)

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

<预><代码>>>>导入参数解析>>>类 CapitalisedHelpFormatter(argparse.HelpFormatter):... def add_usage(self, usage, actions, groups, prefix=None):...如果前缀是无:...前缀 = '用法:'...返回 super(CapitalisedHelpFormatter, self).add_usage(...用法、动作、组、前缀)...>>>parser = argparse.ArgumentParser(add_help=False, formatter_class=CapitalisedHelpFormatter)>>>parser._positionals.title = '位置参数'>>>parser._optionals.title = '可选参数'>>>parser.add_argument('-v', '--version', action='version',... version='%(prog)s 1.0', help="显示程序的版本号并退出.")_VersionAction(option_strings=['-v', '--version'], dest='version', nargs=0, const=None, default='==SUPPRESS==', type=None, choice=None, help="显示程序的版本号并退出.", metavar=None)>>>parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,... help='显示此帮助信息并退出.')_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, selection=None, help='显示此帮助信息并退出.', metavar=None)>>>打印(解析器.format_help())用法:[-v] [-h]可选参数:-v, --version 显示程序的版本号并退出.-h, --help 显示此帮助信息并退出.

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.

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?

解决方案

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.

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.')

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'

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.

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天全站免登陆