从Python的配置文件读取布尔条件 [英] reading boolean condition from config file in Python

查看:809
本文介绍了从Python的配置文件读取布尔条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中使用 ConfigParser json 从配置文件中读取条件的最佳方法是什么?我想读如下:

  [mysettings] 
x> = 10
y& 5

,然后将其应用于 x y 是定义的变量,并且条件将应用于代码中的 x,y 。例如:

  l = get_lambda(settings [mysettings] [0])
如果l :
#do something
pass
l2 = get_lambda(settings [mysettings] [1])$ ​​b $ b如果l2(y):
#do something
pass

理想情况下,我想指定 x + y > = 6



必须有更好的方法,但是想法是使用简单的布尔表达式来限制变量的值


解决方案

假设您有一个名为 conds.ini的配置文件从包含以下内容的受信任源:

  [mysettings ] 
cond1:x> = 10
cond2:y< 5
cond3:x + y> = 6

解析它:

  import ConfigParser 

cp = ConfigParser.ConfigParser()
cp .read('conds.ini')

conds = []
conds.append(cp.get('mysettings','cond1'))
conds.append cp.get('mysettings','cond2'))
conds.append(cp.get('mysettings','cond3'))

#或者你可以做一次读取所有的内容
#conds = [expr的名称,expr在cp.items('mysettings')
#如果name.startswith('cond')]

x = 8
y = 3
for cond in conds:
truthiness = eval('bool({})'format(cond))
print'{}:{}' .format(cond,truthiness)

这将导致以下输出:

  x> = 10:False 
y< 5:True
x + y> = 6:True


What's the best way to read a condition from a config file in Python using ConfigParser and json? I want to read something like:

[mysettings]
x >= 10
y < 5

and then apply it to code where x and y are defined variables, and the condition will be applied as to the values of x, y in the code. Something like:

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

ideally I'd like to specify conditions like x + y >= 6 too.

there must be a better way, but the idea is to constrain the values of variables using simple boolean expressions from the config file.

解决方案

Say you had a config file named conds.ini from a trusted source that contained this:

[mysettings]
cond1: x >= 10
cond2: y < 5
cond3: x + y >= 6

You could do things like the following to parse it:

import ConfigParser

cp = ConfigParser.ConfigParser()
cp.read('conds.ini')

conds = []
conds.append(cp.get('mysettings', 'cond1'))
conds.append(cp.get('mysettings', 'cond2'))
conds.append(cp.get('mysettings', 'cond3'))

# alternatively you could do the following to read them all at once
# conds = [expr for name, expr in cp.items('mysettings') 
#          if name.startswith('cond')]

x = 8
y = 3
for cond in conds:
    truthiness = eval('bool({})'.format(cond))
    print '{}: {}'.format(cond, truthiness)

Which would result in the following output:

x >= 10: False
y < 5: True
x + y >= 6: True

这篇关于从Python的配置文件读取布尔条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆