python include的功能_在Python的Config中增加Include功能
在python中配置文件分析我一般都用configparser。
很好,符合我的一貫需求。
文本格式、簡(jiǎn)單、內(nèi)置。
如:
[db]
host=localhost
user=dl
passwd=12345678
[other]
因?yàn)樾〕绦蜉^多,分別在不同地方,但是都有些共同的配置(如DB的配置)。
如果能在配置文件中include這些共同配置的話,一旦有變化,則只需要修改起一個(gè)地方即可。
研究了下,沒發(fā)現(xiàn)原聲的這個(gè)功能,稍微修改下,寫個(gè)獨(dú)立的讀取配置的函數(shù)即可。
上代碼了.
def getConfig(configfile,section,includesection="include"):
"""
返回某個(gè)配置文件的某個(gè)section的內(nèi)容,以dict形式返回.
增加一個(gè)include的內(nèi)容區(qū)域,這樣可以進(jìn)行包含.
[include]
files : included_file_path(絕對(duì)路徑/configfile的相對(duì)路徑)
"""
conf = ConfigParser.ConfigParser()
conf.readfp(open(configfile))
isections = []
try:
i = dict(conf.items(includesection))
for x in StringIO.StringIO(i.get('files','')):
if os.path.isabs(x):
d = x
else:
d = os.path.join(os.path.dirname(configfile),x)
v = getConfig(d,section,includesection)
if v:
isections.append(v)
except ConfigParser.NoSectionError:
pass
v = {}
try:
v = dict(conf.items(section))
except ConfigParser.NoSectionError:
pass
for d in isections:
for x in d:
if x not in v:
v[x] = d[x]
return v
測(cè)試下.
1.cfg
[include]
files=db.cfg
[test]
xixi=1234
db.cfg
[db]
host=localhost
user=dl
測(cè)試代碼
for k,v in getConfig('1.cfg','db').iteritems():
print k,v
總結(jié)
以上是生活随笔為你收集整理的python include的功能_在Python的Config中增加Include功能的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理查森外推法 matlab,数值代数–理
- 下一篇: python难度如何_【经验分享】想转行