我认为您不想或不需要同时使用两者configparser
and json
,因为两者本身就足够了。以下是对每一项进行操作的方法:
假设您有一个配置文件trusted包含类似内容的源:
myconfig.ini
[mysettings]
other=stuff
conds=
x >= 10
y < 5
x + y >= 6
它可以像这样解析和使用:
from __future__ import print_function
try:
import configparser
except ImportError: # Python 2
import ConfigParser as configparser
get_lambda = lambda expr: lambda **kwargs: bool(eval(expr, kwargs))
cp = configparser.ConfigParser()
cp.read('myconfig.ini')
exprs = cp.get('mysettings', 'conds').strip()
conds = [expr for expr in exprs.split('\n')]
l = get_lambda(conds[0])
l2 = get_lambda(conds[1])
l3 = get_lambda(conds[2])
def formatted(l, c, **d):
return '{:^14} : {:>10} -> {}'.format(
', '.join('{} = {}'.format(var, val) for var, val in sorted(d.items())), c, l(**d))
l = get_lambda(conds[0])
print('l(x=42): {}'.format(l(x=42)))
print()
print(formatted(l, conds[0], x=42))
print(formatted(l2, conds[1], y=6))
print(formatted(l3, conds[2], x=3, y=4))
这将导致以下输出:
l(x=42): True
x = 42 : x >= 10 -> True
y = 6 : y < 5 -> False
x = 3, y = 4 : x + y >= 6 -> True
如果信息保存在类似于以下的 JSON 格式文件中:
myconfig.json
{
"mysettings": {
"other": "stuff",
"conds": [
"x >= 10",
"y < 5",
"x + y >= 6"
]
}
}
它可以很容易地解析为json
模块并以类似的方式使用:
import json
with open('myconfig.json') as file:
settings = json.loads(file.read())
conds = settings['mysettings']['conds']
...其余部分将是相同的并产生相同的结果。 IE。:
l = get_lambda(conds[0])
print('l(x=42): {}'.format(l(x=42)))
print()
print(formatted(l, conds[0], x=42))
print(formatted(l2, conds[1], y=6))
print(formatted(l3, conds[2], x=3, y=4))