从配置文件读取布尔条件?

2024-02-28

使用Python从配置文件中读取条件的最佳方法是什么ConfigParser and json?我想读一些类似的内容:

[mysettings]
x >= 10
y < 5

然后将其应用到代码中x and y是已定义的变量,并且条件将应用于x, y在代码中。就像是:

l = get_lambda(settings["mysettings"][0])
if l(x):
  # do something
  pass
l2 = get_lambda(settings["mysettings"][1])
if l2(y):
  # do something
  pass

理想情况下,我想指定条件,例如x + y >= 6 too.

一定有更好的方法,但其想法是使用配置文件中的简单布尔表达式来约束变量的值。


我认为您不想或不需要同时使用两者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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从配置文件读取布尔条件? 的相关文章

随机推荐