Argparse:在"--help"中包括默认值的方法吗? [英] Argparse: Way to include default values in '--help'?

查看:130
本文介绍了Argparse:在"--help"中包括默认值的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下argparse代码段:

Suppose I have the following argparse snippet:

diags.cmdln_parser.add_argument( '--scan-time',
                     action  = 'store',
                     nargs   = '?',
                     type    = int,
                     default = 5,
                     help    = "Wait SCAN-TIME seconds between status checks.")

当前,--help返回:

usage: connection_check.py [-h]
                             [--version] [--scan-time [SCAN_TIME]]

          Test the reliability/uptime of a connection.



optional arguments:
-h, --help            show this help message and exit
--version             show program's version number and exit
--scan-time [SCAN_TIME]
                    Wait SCAN-TIME seconds between status checks.

我更喜欢这样的东西:

--scan-time [SCAN_TIME]
                    Wait SCAN-TIME seconds between status checks.
                    (Default = 5)

浏览帮助格式化程序代码显示了有限的选项.是否有一种聪明的方法让argparse以类似的方式打印--scan-time的默认值,还是我应该将help格式化程序作为子类?

Peeking at the help formatter code revealed limited options. Is there a clever way to get argparse to print the default value for --scan-time in a similar fashion, or should I just subclass the help formatter?

推荐答案

使用 argparse.ArgumentDefaultsHelpFormatter格式化程序:

Use the argparse.ArgumentDefaultsHelpFormatter formatter:

parser = argparse.ArgumentParser(
    # ... other options ...
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

引用文档:

另一个可用的格式化程序类ArgumentDefaultsHelpFormatter将添加有关每个参数默认值的信息.

The other formatter class available, ArgumentDefaultsHelpFormatter, will add information about the default value of each of the arguments.

请注意,这仅适用于已定义帮助文本的参数;没有参数的help值,没有帮助消息可将有关默认值的信息添加到.

Note that this only applies to arguments that have help text defined; with no help value for an argument, there is no help message to add information about the default value to.

然后,您的扫描时间选项的确切输出将变为:

The exact output for your scan-time option then becomes:

  --scan-time [SCAN_TIME]
                        Wait SCAN-TIME seconds between status checks.
                        (default: 5)

这篇关于Argparse:在"--help"中包括默认值的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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