我正在使用 argparse
模块来设置我的命令行选项。我还在我的应用程序中使用 dict
作为配置。简单的键/值存储。
我正在寻找的是使用命令行参数覆盖 JSON 选项的可能性,而无需提前定义所有可能的参数。像 --conf-key-1 value1 --conf-key-2 value2
这样的东西,它会创建一个字典 {'key_1': 'value1','key_2': 'value2' }
(参数中的“-”在字典中被替换为“_”)。然后我可以将这个字典与我的 JSON 配置 (dict) 结合起来。
所以基本上我想将 --conf-*
定义为参数,其中 *
可以是任何键,后面是 value
.
我确实找到了 configargparse
模块,但据我所知,我从我已经使用过的 dict
开始。
有什么想法可以解决这个问题吗?
最佳答案
我有一个类似的问题,并找到了一个非常可行的模式,可以很好地与 argparse 一起工作(这里是三个键对:foo、bar 和 baz:
mycommand par1 --set foo=hello bar="hello world" baz=5
1。定义可选的多值参数
set 参数必须这样定义:
import argparse
parser = argparse.ArgumentParser(description="...")
...
parser.add_argument("--set",
metavar="KEY=VALUE",
nargs='+',
help="Set a number of key-value pairs "
"(do not put spaces before or after the = sign). "
"If a value contains spaces, you should define "
"it with double quotes: "
'foo="this is a sentence". Note that '
"values are always treated as strings.")
args = parser.parse_args()
参数是可选的和多值的,最少出现一次 (nargs='+'
)。
结果是字符串的列表,例如["foo=hello", "bar=hello world", "baz=5"]
in args.set
,我们现在需要解析(注意 shell 如何已处理并删除引号!)。
2。解析结果
为此我们需要 2 个辅助函数:
def parse_var(s):
"""
Parse a key, value pair, separated by '='
That's the reverse of ShellArgs.
On the command line (argparse) a declaration will typically look like:
foo=hello
or
foo="hello world"
"""
items = s.split('=')
key = items[0].strip() # we remove blanks around keys, as is logical
if len(items) > 1:
# rejoin the rest:
value = '='.join(items[1:])
return (key, value)
def parse_vars(items):
"""
Parse a series of key-value pairs and return a dictionary
"""
d = {}
if items:
for item in items:
key, value = parse_var(item)
d[key] = value
return d
此时就很简单了:
# parse the key-value pairs
values = parse_vars(args.set)
你现在有一个字典:
values = {'foo':'hello', 'bar':'hello world', 'baz':'5'}
请注意值如何始终作为字符串返回。
此方法也记录为 git gist .
关于python - 使用 argparse (python) 创建变量键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27146262/