问题描述
我正在尝试通过使用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,因为我不想限制键/值的数量和名称.它将有助于将来支持新的密钥/值.
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时必须使用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对吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!