How to evaluate simple math expressions in config files
I would like to use a configuration file with some simple math expressions like adding or substracting.
For example:[section]
a = 10
b = 15
c = a-5
d = b+c
Is there any way to do this using a ConfigParser module? I found some examples of using strings as a kind of variables in config files, but if i'm using it i get a not evaluated strings (and i have to parse it in my python code).
If it's not possible in ConfigPars开发者_Go百科er is there any module you recommend?
Why use ConfigParser? Why not just
config.py:
a = 10
b = 15
c = a-5
d = b+c
script.py:
import config
print(config.c)
# 5
print(config.d)
# 20
One approach that some projects use is to make your configuration file a Python module. Then simply import it (or use exec
) to run the contents. That gives you a lot of power, although obviously there are some security concerns depending on where you use it ("just paste these lines into your .whateverrc.py file...").
If you must you can do something like this:
example.conf :
[section]
a = 10
b = 15
c = %(a)s+%(b)s
d = %(b)s+%(c)s
and in your script you can do:
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'
and you can eval the expression :
print eval(config.get('section', 'c'))
# 25
print eval(config.get('section', 'd'))
# 40
If i may suggest i think that ConfigParser modules classes are missing a function like this, i think the get() method should allow to pass a function that will eval the expression :
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
精彩评论