`

python 使用ConfigParser,ConfigObj读取配置

阅读更多
使用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:
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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics