簡體   English   中英

從配置文件中讀取布爾條件?

[英]reading boolean condition from config file?

使用ConfigParserjson從Python中的配置文件中讀取條件的最佳方法是什么? 我想讀類似的東西:

[mysettings]
x >= 10
y < 5

然后將其應用於xy定義變量的代碼,條件將應用於代碼中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這樣的條件。

必須有更好的方法,但想法是使用配置文件中的簡單布爾表達式約束變量的值。

這是一個使用Python本身作為描述配置文件的語言的示例:

config.py

mysettings = [
    lambda x: x >= 10,
    lambda y: y < 5,
]

main.py

from config import mysettings

a = 42
b = 300

for i, condition in enumerate(mysettings):
    for value in (a, b):
        result = condition(value)
        print "condition %s for value %s is: %s" % (i, value, result)

輸出:

condition 0 for value 42 is: True
condition 0 for value 300 is: True
condition 1 for value 42 is: False
condition 1 for value 300 is: False

這當然假設配置文件被認為是可信輸入,因為通過執行condition(value)您將執行配置文件中定義的任何功能。

但是,無論你使用什么語言,我都沒有看到任何方法:條件是表達式 ,因此是可執行代碼 如果您希望最終得到一個可以在代碼中使用的Python表達式,那么您遲早要評估該表達式。

編輯:

如果由於某種原因你真的不能使用Python,那么你可以使用JSON中的配置文件來實現它:

config.json

{
  "mysettings": {
    "color": "Blue",
    "expressions": [
      "x >= 10",
      "y < 5"
    ]
  },
  "other_settings": {
    "color": "red"
  }
}

main.py

import json

x = 42
y = 300


def eval_expr(expr, values):
    result = eval(expr, values.copy())
    print "The expression '%s' evaluates to '%s' for the values %r" % (
                                                    expr, result, values)
    return result


f = open('config.json')
data = json.loads(f.read())
settings = data["mysettings"]

for expr in settings['expressions']:
    values = dict(x=x, y=y)
    eval_expr(expr, values)

結果:

The expression 'x >= 10' evaluates to 'True' for the values {'y': 300, 'x': 42}
The expression 'y < 5' evaluates to 'False' for the values {'y': 300, 'x': 42}

或者,更接近你的例子:

x = 1
y = 2
values = dict(x=x, y=y)

e1 = settings['expressions'][0]
if eval_expr(e1, values):
    # do something
    pass

e2 = settings['expressions'][1]
if eval_expr(e2, values):
    # do something else
    pass

結果:

The expression 'x >= 10' evaluates to 'False' for the values {'y': 2, 'x': 1}
The expression 'y < 5' evaluates to 'True' for the values {'y': 2, 'x': 1}

我認為你不想 - 或者不需要同時使用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM