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
值,则没有帮助消息来添加有关默认值 to 的信息.
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屋!