如何将python中的命令行参数转换为字典?

2024-04-28 19:48:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个应用程序,它接受任意命令行参数,然后将它们传递到python函数:

$ myscript.py --arg1=1 --arg2=foobar --arg1=4

然后在myscript.py中:

import sys
argsdict = some_function(sys.argv)

其中argsdict如下所示:

{'arg1': ['1', '4'], 'arg2': 'foobar'}

我肯定某个地方有一个图书馆能做到这一点,但我什么也找不到。

编辑:argparse/getopt/optparse不是我要找的。这些库用于定义每个调用都相同的接口。我需要能够处理任意的论点。

除非,argparse/optparse/getopt具有执行此操作的功能。。。


Tags: 函数命令行pyimport应用程序参数sysargparse
3条回答

下面是一个使用argparse的示例,尽管这是一个扩展。我不认为这是一个完整的解决方案,而是一个好的开始。

class StoreInDict(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        d = getattr(namespace, self.dest)
        for opt in values:
            k,v = opt.split("=", 1)
            k = k.lstrip("-")
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
        setattr(namespace, self.dest, d)

# Prevent argparse from trying to distinguish between positional arguments
# and optional arguments. Yes, it's a hack.
p = argparse.ArgumentParser( prefix_chars=' ' )

# Put all arguments in a single list, and process them with the custom action above,
# which convertes each "--key=value" argument to a "(key,value)" tuple and then
# merges it into the given dictionary.
p.add_argument("options", nargs="*", action=StoreInDict, default=dict())

args = p.parse_args("--arg1=1 --arg2=foo --arg1=4".split())
print args.options

…我是否可以问一下你为什么要重写(一堆)轮子,当你有:

是吗?

编辑:

在回复您的编辑时,optparse/argparse(后一个仅在>;=2.7中可用)具有足够的灵活性,可以扩展以满足您的需要,同时保持一致的接口(例如,用户希望能够同时使用--arg=value--arg value-a value-avalue等。。使用预先存在的库,您不必担心支持所有这些语法等)。

你可以用这样的东西:

myscript.py

import sys
from collections import defaultdict

d=defaultdict(list)
for k, v in ((k.lstrip('-'), v) for k,v in (a.split('=') for a in sys.argv[1:])):
    d[k].append(v)

print dict(d)

结果:

C:\>python myscript.py  --arg1=1 --arg2=foobar --arg1=4
{'arg1': ['1', '4'], 'arg2': ['foobar']}

注:该值将始终是一个列表,但我认为这更为一致。如果你真的想把最终的字典

{'arg1': ['1', '4'], 'arg2': 'foobar'}

然后你就可以跑了

for k in (k for k in d if len(d[k])==1):
    d[k] = d[k][0]

之后。

相关问题 更多 >