Parse non-pre-defined argument

淺唱寂寞╮ 提交于 2019-12-20 04:08:01

问题


Is there any library that can parse random key value pairs in sys.argv in Python?

For example:

 python run.py --v1 k1 --v2 k2 --v3 k3

Should return me a dictionary like {v1->k1, v2->k2, v3->k3}. and at compile time I don't know what those 'v' will be.

Thanks!

Erben


回答1:


It's kind of hacky, but you do have this:

import argparse
import collections
parser = argparse.ArgumentParser()
known, unknown_args = parser.parse_known_args()

unknown_options = collections.defaultdict(list)
key = None
for arg in unknown_args:
    if arg.startswith('--'):
        key = arg[2:]
    else:
        unknown_options[key].append(arg)



回答2:


d = {}
for i,arg in enumerate(sys.argv):
    if arg.startswith("--"):
        d[arg[2:]] = sys.argv[i+1]

print d



回答3:


In a newer Python that uses dictionary comprehension you could use a one liner like this:

ll = sys.argv[1:]
args = {k[2:]:v for k,v in zip(ll[::2], ll[1::2])}
# {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}

It doesn't have any flexibility in case your user screws up the pairing, but it would be a quick start.

A generator could be used to pop pairs of strings off the sys.argv[1:]. This would be a good place to build in flexibility and error checking.

def foo(ll):
    ll = iter(ll)
    while ll:
        yield ll.next()[2:], ll.next()
{k:v for k,v in foo(ll)}


来源:https://stackoverflow.com/questions/21920989/parse-non-pre-defined-argument

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