官方文档:http://docs.python.org/library/configparser.html
主要用到两个类
写配置:ConfigParse.RawConfigParse类
读配置:ConfigParse.ConfigParse类
一、ConfigParse.RawConfigParse
>>> import ConfigParser
>>> config=ConfigParser.RawConfigParser()
查看写的类有那些方法
>>> dir(config)
['OPTCRE', 'OPTCRE_NV', 'SECTCRE', '__doc__', '__init__', '__module__', '_boolean_states', '_defaults', '_dict', '_get', '_optcre', '_read', '_sections', 'add_section', 'defaults', 'get', 'getboolean', 'getfloat', 'getint', 'has_option', 'has_section', 'items', 'options', 'optionxform', 'read', 'readfp', 'remove_option', 'remove_section', 'sections', 'set', 'write']
写配置文件
1 #!/bin/env python 2 import ConfigParser 3 4 config=ConfigParser.RawConfigParser() 5 6 confdict={} 7 confdict['id']=99 8 confdict['package']='rpm' 9 confdict['timeout']=150 10 11 config.add_section('redhat')#增加section 12 13 config.set('redhat','id',confdict['id']) #增加option 14 config.set('redhat','id',confdict['id']) 15 config.set('redhat','package',confdict['package']) 16 config.set('redhat','timeout',confdict['timeout']) 17 #写入文件中 18 with open('/tmp/redhat.conf','w') as myconf:config.write(myconf)
jin:~ # python redhatconf.py
jin:~ # cat /tmp/redhat.conf
[redhat]
id = 99
package = rpm
timeout = 150
多一行空行,why?
二、 ConfigParse.ConfigParse
查看读的类有那些方法
>>> config = ConfigParser.ConfigParser()
>>> dir(config)
['OPTCRE', 'OPTCRE_NV', 'SECTCRE', '_KEYCRE', '__doc__', '__init__', '__module__', '_boolean_states', '_defaults', '_dict', '_get', '_interpolate', '_interpolation_replace', '_optcre', '_read', '_sections', 'add_section', 'defaults', 'get', 'getboolean', 'getfloat', 'getint', 'has_option', 'has_section', 'items', 'options', 'optionxform', 'read', 'readfp', 'remove_option', 'remove_section', 'sections', 'set', 'write']
读配置文件
1 #!/bin/env python 2 import ConfigParser 3 4 config=ConfigParser.ConfigParser() 5 6 config.read('/tmp/redhat.conf') 7 8 if config.has_option('redhat','id'): 9 print config.get('redhat','id') 10 11 print config.sections() 12 print config.get('redhat','package') 13 print config.get('redhat','timeout')
python readredhatconf.py
99
['redhat']
rpm
150
以上是使用模块的方式,下面是网友Mike_Zhang通过列表解析和字典自定函数解析ini配置文件
http://www.cnblogs.com/MikeZhang/archive/2011/11/19/2255169.html
配置文件格式
/root/test/conf
<global>
shell = all
sql = ['s1', 'k1', 'c1']
脚本内容
1 #! /usr/bin/python 2 #-*- coding: utf-8 -*- 3 sectionLable = ("<",">") 4 endlineLable = "\n" 5 equalLable = "=" 6 noteLable = '#' 7 8 def getSectionMap(strtmp,lable1 = sectionLable): 9 tmp = strtmp.split(lable1[0]) 10 tmp = [elem for elem in tmp if len(elem) > 1] 11 tmp = [elem for elem in tmp if elem.rfind(lable1[1]) > 0] 12 sectionDict = {} 13 for elem in tmp: 14 key = elem[0:elem.find(lable1[1]):] 15 value = elem[elem.find(endlineLable)+len(endlineLable)::] 16 sectionDict[key] = value 17 return sectionDict 18 19 def getValueMap(strtmp): 20 tmp = strtmp.split(endlineLable) 21 tmp = [elem for elem in tmp if len(elem) > 1] 22 valueDict = {} 23 for elem in tmp: 24 if elem.find(noteLable) > 0: 25 elem = elem[0:elem.find(noteLable):] 26 elem = ''.join(elem.split()) 27 key = elem[0:elem.find(equalLable):] 28 value = elem[elem.find(equalLable)+len(equalLable)::] 29 valueDict[key] = value 30 return valueDict 31 f = open(raw_input("Input file name : "),"rb") 32 strFileContent = f.read() 33 f.close() 34 var = getSectionMap(strFileContent) 35 dict = {} 36 for k,v in var.items(): 37 var2 = getValueMap(v) 38 dict[k] = var2 39 print dict
201203 ini配置文件解析实战:
ini配置文件模块ConfigParse #vim sjgame.ini [Login_svrlist] createchar=/data/sjgame/Logind/ switchsvr=/data/sjgame/Logind/ logind=/data/sjgame/Logind #!/usr/bin/env python import ConfigParser def readConfig(file="sjgame.ini"): Config=ConfigParser.ConfigParser() #创建对象ConfigParser Config.read(file) #读取配置文件 sections=Config.sections() #获取配置文件里的sections #print sections for section in sections: #print section #section名字 Login_svrlist #print Config.items(section) #每个section的内容 [('createchar', '/data/sjgame/Logind/'), ('switchsvr', '/data/sjgame/Logind/'), ('logind', '/data/sjgame/Logind/')]#这里是key和value组成的元组,再构成列表。 config_dict={} #设置一个空字典,我们要k和v组成字典 for conf in Config.items(section): #遍历每个section里列表 #print conf #conf就是key和value组成的元组 servicename=conf[0] #获取元组里k servicedir=conf[1] #获取元组里的v #print servicename #print servicedir config_dict[servicename]=servicedir #将key和value对应添加到字典里 #print config_dict return config_dict #配置文件字典 if __name__=='__main__': print readConfig() 多section选择输出的section ofreebsd# cat sjgame.ini [Login_svrlist] createchar=/data/sjgame/Logind/ switchsvr=/data/sjgame/Logind/ logind=/data/sjgame/Logind/ [Service_svrlist] dbcom3=/data/sjgame/service/runlib/ service=/data/sjgame/service/runlib/ #!/usr/bin/env python import ConfigParser def readConfig(file="sjgame.ini",section=''): Config=ConfigParser.ConfigParser() Config.read(file) sections=Config.sections() #print sections config_dict={} for conf in Config.items(section): servicename=conf[0] servicedir=conf[1] config_dict[servicename]=servicedir return config_dict if __name__=='__main__': print readConfig(section='Service_svrlist') #读取配置文件时指定要读哪个setction #Ser_list=readConfig(section='Service_svrlist') #可以出来赋值给变量 #print Ser_list 配置文件的里的value是列表 ofreebsd# vim sjgame.ini [Login_svrlist] createchar=/data/sjgame/Logind/ switchsvr=/data/sjgame/Logind/ logind=/data/sjgame/Logind/ order=['createchar','switchsvr','logind'] desc=['logind','switchsvr','createchar'] [Service_svrlist] dbcom3=/data/sjgame/service/runlib/ service=/data/sjgame/service/runlib/ # python ConfigParsetest.py {'createchar': '/data/sjgame/Logind/', 'order': "['createchar','switchsvr','logind']", 'switchsvr': '/data/sjgame/Logind/', 'desc': "['logind','switchsvr','createchar']", 'logind': '/data/sjgame/Logind/'} 打印K的内容 if __name__=='__main__': #print readConfig(section='Service_svrlist') Ser_list=readConfig(section='Login_svrlist') print Ser_list['desc'] # python ConfigParsetest.py ['logind','switchsvr','createchar']