我正在使用argparsepython库。在某些时候,我使用一个名为param2 的参数,称为参数:一个键和一个值。我使用的代码行如下:
parser.add_argument("-p", "--param", nargs=2, action="append",
help="key and value for query",
type=str, metavar="key value"
)
Run Code Online (Sandbox Code Playgroud)
出问题了,当我致电帮助时,它显示如下:
optional arguments:
-h, --help show this help message and exit
-p key value key value, --param key value key value
key and value for query parameters
Run Code Online (Sandbox Code Playgroud)
名称“键值”重复两次。我尝试使用列表和生成器,但是我发现的唯一方法是创建一个包含不同值的小类,并在要求__str__这样时产生它们:
class Meta:
def __init__(self, iterable):
self.gene = itertools.cycle(iterable)
def __str__(self):
return self.gene.__next__()
Run Code Online (Sandbox Code Playgroud)
我这样打电话add_argument:
parser.add_argument("-p", "--param", nargs=2, action="append",
help="key and value for query parameters",
type=str, metavar=Meta(["key", "value"])
)
Run Code Online (Sandbox Code Playgroud)
并且它正确显示:
-p key value, --param key value
key and value for query parameters
Run Code Online (Sandbox Code Playgroud)
但是我发现使用像这样的临时类非常丑陋Meta,而且我觉得必须有另一种(更好的)方式来做到这一点。我做对了吗?
通过深入滚动文档,我找到了答案
不同的nargs值可能会导致metavar多次使用。为metavar提供元组会为每个参数指定不同的显示方式:
确实,这很好用:
parser.add_argument("-p", "--param", nargs=2, action="append",
help="key and value for query parameters",
type=str, metavar=("key", "value")
)
Run Code Online (Sandbox Code Playgroud)