在python的Config中增加include功能

在python中配置文件分析我一般都用configparser。
很好,符合我的一贯需求。
文本格式、简单、内置。
如:

[db]
host=localhost
user=dl
passwd=12345678
[other]

因为小程序较多,分别在不同地方,但是都有些共同的配置(如DB的配置)。
如果能在配置文件中include这些共同配置的话,一旦有变化,则只需要修改起一个地方即可。
研究了下,没发现原声的这个功能,稍微修改下,写个独立的读取配置的函数即可。
上代码了.

def getConfig(configfile,section,includesection="include"):
    """
        返回某个配置文件的某个section的内容,以dict形式返回.
        增加一个include的内容区域,这样可以进行包含.
        [include]
        files : included_file_path(绝对路径/configfile的相对路径)
    """
    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

 测试下.
1.cfg

[include]
files=db.cfg
[test]
xixi=1234

db.cfg

[db]
host=localhost
user=dl

测试代码

for k,v in getConfig('1.cfg','db').iteritems():
    print k,v

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。