Can argparse accept argument value as key=val pairs

孤者浪人 提交于 2019-12-02 06:54:43

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='*')

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

And it should work

I would use type=str and parse it later, perhaps with json, but the main problem with that would be the way you are writing your command:

cli.py --conf key1=value1, key2=value2, kay3=value3

The spaces split each pair to a different argument. If you use either method you suggested it would not work. Instead make sure that they are all one argument:

cli.py --conf="key1='value1', key2='value2', kay3='value3'"

That way this large argument is ready to be parsed as json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!