argparse:没有存储值的参数的无关参数?

argparse: extraneous arguments for argument with no stored value?

Python 中的 argparse 有点问题...

import argparse

parser = argparse.ArgumentParser()
parser.add_argument ("-o", "--optional", help="this is an optional argument")
args = parser.parse_args()

print ( args.optional )

调用test.py -h会输出...

usage: test.py [-h] [-o OPTIONAL]

optional arguments:
  -h, --help            show this help message and exit
  -o OPTIONAL, --optional OPTIONAL
                        this is an optional argument

有什么方法可以去掉帮助菜单中多余的 OPTIONAL 吗?我知道我可以用 parser.add_argument ("-o", "--optional", help="this is an optional argument", action=store_true) 做到这一点,但我不能,因为我需要稍后调用 args.optional

同样,这与其说是程序的功能,不如说是美观,因为 test.py -o hello 会打印 hello.

通常没有参数的选项有一个 action,这将抑制元变量:

parser.add_argument ("-o", "--optional", action='store_true')

否则,您可以这样修改参数:

parser.add_argument ("-o", "--optional", metavar='', help="the help text")

首先是关于这个参数的解析还是帮助中的显示?

parser.add_argument ("-o", "--optional", help="this is an optional argument")

具有默认的 store_true 操作,因此采用一个参数。如用法所示:

usage: test.py [-h] [-o OPTIONAL]

其中 'OPTIONAL' 是您将包含在 -o--optional 之后的字符串的替代。 args.optional 将具有该字符串的值。

action='store_true 将此参数转换为布尔值,如果未给出则为 False,如果提供了 -o 则为 True。它不需要任何附加值。

-o OPTIONAL, --optional OPTIONAL

是像这样的操作在帮助中显示的正常方式。同样,OPTIONAL-o--optional 之后的字符串的位置标记。 metavar 参数可用于自定义该地点标记。可以短到 "".

有些人不喜欢这种重复的模式,更喜欢

-o , --optional OPTIONAL

这在之前的问题中已经讨论过了。它需要更改 HelpFormatter class(即 subclassing)。

python argparse help message, disable metavar for short options?

还有一个就是简化定义

parser.add_argument ("-o", dest="optional", help="this is an optional argument")