2011-01-11 25 views
3

我想用一些簡單的數學表達式(如添加或減少)來使用配置文件。
例如:如何在配置文件中評估簡單的數學表達式

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

有沒有辦法做到這一點使用一個configparser模塊用來?我發現一些使用字符串作爲配置文件中的一種變量的例子,但是如果我使用它,我會得到一個沒有評估過的字符串(並且我必須在我的python代碼中解析它)。

如果在ConfigParser中不可行,那麼您推薦使用哪個模塊?

+5

計算是不是有什麼配置文件是給。 – SilentGhost 2011-01-11 13:29:41

+1

@SilentGhost:你不應該做太多的處理,但有些情況下你想說「x比y大5」,同時能夠改變y。這比指定x_ydiff和整理優先規則等要好得多。 – 2011-01-11 13:51:06

+0

你可以使用Vinay Sajip的[`config``模塊](http://www.red-dove.com/config-doc),這是他在comp.lang.python [ConfigParserShootout]中的條目(http:// wiki。 python.org/moin/ConfigParserShootout),它允許在配置文件中使用[使用表達式](http://www.red-dove.com/config-doc/#using-expressions)。或者,你可以很容易地使用[pyparsing - Examples]中的Steven Siew的[SimpleCalc.py](http://pyparsing.wikispaces.com/file/view/SimpleCalc.py)(http:// pyparsing)。 wikispaces.com/Examples)頁面。 – martineau 2011-01-11 18:42:46

回答

9

爲什麼使用ConfigParser?爲什麼不

config.py:

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

script.py:

import config 
print(config.c) 
# 5 
print(config.d) 
# 20 
2

一種方法,一些項目採用的是讓你的配置文件的Python模塊。然後只需導入它(或使用exec)來運行內容。這給了你很大的力量,但顯然有一些安全問題取決於你在哪裏使用它(「只需將這些行粘貼到你的.whateverrc.py文件中......」)。

2

如果你必須你可以做這樣的事情:

example.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' 

,您可以EVAL表達:

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

如果我可以建議我認爲ConfigParser模塊類缺少這樣的功能,我覺得get()方法應允許通過將EVAL表達的功能:

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