+-
python – 从配置文件中读取布尔条件?
使用ConfigParser和json从 Python中的配置文件中读取条件的最佳方法是什么?我想读类似的东西:

[mysettings]
x >= 10
y < 5

然后将其应用于x和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这样的条件.

必须有更好的方法,但想法是使用配置文件中的简单布尔表达式约束变量的值.

最佳答案
我认为你不想 – 或者不需要同时使用configparser和json,因为两者本身就足够了.以下是如何使用每个方法:

假设您有一个来自可靠来源的配置文件,其中包含以下内容:

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']

……其余部分将是相同的并产生相同的结果.即:

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))
点击查看更多相关文章

转载注明原文:python – 从配置文件中读取布尔条件? - 乐贴网