3

我想使用带有一些简单数学表达式的配置文件,例如加法或减法。
例如:

[section]
a = 10
b = 15
c = a-5
d = b+c

有没有办法使用 ConfigParser 模块来做到这一点?我发现了一些在配置文件中使用字符串作为一种变量的示例,但是如果我使用它,我会得到一个未评估的字符串(并且我必须在我的 python 代码中解析它)。

如果在 ConfigParser 中不可能,您推荐任何模块吗?

4

3 回答 3

9

为什么使用 ConfigParser?为什么不只是

配置文件:

a = 10
b = 15
c = a-5
d = b+c

脚本.py:

import config
print(config.c)
# 5
print(config.d)
# 20
于 2011-01-11T13:29:40.747 回答
2

一些项目使用的一种方法是使您的配置文件成为 Python 模块。然后只需将其导入(或使用exec)即可运行内容。这为您提供了很大的功能,尽管显然存在一些安全问题,具体取决于您使用它的位置(“只需将这些行粘贴到您的 .whateverrc.py 文件中......”)。

于 2011-01-11T13:29:55.870 回答
2

如果必须,您可以执行以下操作:

示例.conf:

[section]
a = 10
b = 15
c = %(a)s+%(b)s
d = %(b)s+%(c)s

在您的脚本中,您可以执行以下操作:

import ConfigParser

config = ConfigParser.SafeConfigParser()
config.readfp(open('example.conf'))

print config.get('section', 'a')
# '10'
print config.get('section', 'b')
# '15'
print config.get('section', 'c')
# '10+15'
print config.get('section', 'd')
# '15+10+15'

你可以评估表达式:

print eval(config.get('section', 'c'))
# 25
print eval(config.get('section', 'd'))
# 40

如果我可能建议我认为ConfigParser模块类缺少这样的函数,我认为get()方法应该允许传递一个将评估表达式的函数:

def my_get(self, section, option, eval_func=None):

    value = self.get(section, option)
    return eval_func(value) if eval_func else value

setattr(ConfigParser.SafeConfigParser, 'my_get', my_get)


print config.my_get('section', 'c', eval)
# 25

# Method like getint() and getfloat() can just be writing like this:

print config.my_get('section', 'a', int)
# 10
于 2011-01-11T13:55:25.867 回答