Argparse:在"--help"中包括默认值的方法吗? [英] Argparse: Way to include default values in '--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屋!