argparse 可以接受参数值作为 key=val 对 [英] Can argparse accept argument value as key=val pairs
问题描述
我正在尝试使用 argparse 来实现以下选项(由于项目要求,不能使用任何其他工具,如 docopt):-
I am trying to implement below option by using argparse(can't use any other tool like docopt because of project requirement):-
cli.py --conf key1=value1, key2=value2, kay3=value3
or
cli.py --conf key1=value1 key2=value2 key3=value3
到目前为止,我已经尝试过 type=json.loads
或 dict 但没有帮助.一种可能的解决方案是使用 type=str
,然后将其解析为 dict
.你们知道我缺少的任何其他更好的解决方案吗..提前致谢.
So far I have tried type=json.loads
or dict but not helping.
One possible solution is to use type=str
and then later parse it to dict
.
Do you guys know any other better solution which I am missing..
Thanks in advance.
注意 - 不能使用 --key1=value1 --key2=value2 --key3=value3 因为我不想限制键/值的数量和名称.它将有助于将来支持新的 key/val.
Note- Can't use --key1=value1 --key2=value2 --key3=value3 because I don't want to restrict count and name of key/value. It will help in supporting new key/val in future.
推荐答案
既然你评论说你必须像写的那样使用 cli,这是另一个解决方案.在 argparse
中,我会像这样定义 conf
参数:
Since you commented that you must use the cli as it is written, This is another solution. In argparse
i would define the conf
argument like this:
parser.add_argument('--conf', nargs='*')
使用 nargs='*'
之后的所有参数都将在同一个列表中,如下所示 ['key1=value1', 'key2=value2', 'key3=value3']
With nargs='*'
all the arguments following that would be in the same list which looks like this ['key1=value1', 'key2=value2', 'key3=value3']
要解析该列表并从中获取字典,您可以这样做:
To parse that list and get a dict out of it, you can do this:
parsed_conf = {}
for pair in conf:
kay, value = pair.split('=')
parsed_conf[key] = value
现在这样调用你的程序(不带逗号):
Now call your program like this (without commas):
cli.py --conf key1=value1 key2=value2 key3=value3
它应该可以工作
这篇关于argparse 可以接受参数值作为 key=val 对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!