ITeye博客

python 使用ConfigParser,ConfigObj读取配置

essen · 2013-09-25 16:14 · python · 编程语言 · Markdown

使用python 从配置文件获取配置:

import ConfigParser

 config = ConfigParser.ConfigParser()

 #@staticmethod
 def getValue(keyName):
     with open('./conf/system.properties', 'r') as cfg:
         config.readfp(cfg)
         return config.get('config', keyName)

配置文件示例:

[config]
 username = xx
 pwd = xx

但是有一个配置文件并没有上面的section [config],配置文件又不能修改,在网上搜了一个,发现很好玩儿,yeah it's dummy:

Using Python's ConfigParser to read a file without section name

importStringIO
config =StringIO.StringIO()
config.write('[dummysection]\n')
config.write(open('myrealconfig.ini').read())
config.seek(0, os.SEEK_SET)importConfigParser
cp =ConfigParser.ConfigParser()
cp.readfp(config)
somevalue = cp.getint('dummysection','somevalue')

后来发现一个更加简单易用的ConfigObj,不过需要先安装,安装也很容易 pip install configobj

下面是使用

 from configobj import ConfigObj
 config = ConfigObj(filename)
 #
 value1 = config['keyword1']
 value2 = config['keyword2']
 #
 section1 = config['section1']
 value3 = section1['keyword3']
 value4 = section1['keyword4']
 #
 # you could also write
 value3 = config['section1']['keyword3']
 value4 = config['section1']['keyword4']

而且可以读取List列表的配置,只要item之间用','分割就行

如:

workspaces = path1, path2,path3

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。