用python读取配置文件比较方便,比如下面一个配置文件:
0.ini文件:
---------------文件开始----------------
[global]
ip = 192.168.1.100 ;ip地址
port = 1234
MAC = 0x414243444546;mac
---------------文件结束----------------
要从中读取ip地址我们可以用如下代码:
1 #! /usr/bin/python2 #-*- coding: utf-8 -*-3 import ConfigParser
4
5 config = ConfigParser.ConfigParser()
6 config.readfp(open(raw_input("Input file name :"),"rb"))
7
8 print config.get("global","ip")
运行结果:
>>>
Input file name : 0.ini
192.168.1.100
如果把最后一行换成:print config.get("global","MAC")
运行结果:
>>>
Input file name : 0.ini
0x414243444546;mac
然而读取的数据不是我预期的(主要是ini文件写法有误),再看下面我自己定义的配置文件:
1.ini文件:
---------------文件开始----------------
# 配置文件
[global] #全局配置参数
ip = 192.168.1.100
port = 1234
MAC = 0x414243444546# MAC地址
[global] #全局配置参数
ip = 192.168.1.101
port = 1234
MAC = 0x414243444547 # MAC地址
---------------文件结束----------------
对于扩展的配置文件格式,上述代码不能解析。默认的配置有时候局限太大,用起来不太方便。
我们可以借助python的dict数据结构完成配置文件的解析,使用起来也很方便。
下面是个示例,可以读取上述扩展的配置文件。
读取代码示例:
1 #! /usr/bin/python2 #-*- coding: utf-8 -*-3
4 partLable = ("<",">")
5 sectionLable = ("[","]")
6 endlineLable = "\r\n" #windows下的行标志7 #endlineLable = "\n" # linux下的行标志8 equalLable = "=" #赋值标志9 noteLable = '#' #注释标志10
11 #得到总配置的map12 def getPlatformMap(strtmp,lable1 = partLable,lable2 = sectionLable):
13 tmp = strtmp.split(lable1[0])
14 tmp = [elem for elem in tmp if len(elem) > 1]
15 tmp = [elem for elem in tmp if elem.rfind(lable1[1]) > 0]
16 platdict = {}
17 for elem in tmp:
18 key = elem[0:elem.find(lable1[1]):]
19 value = elem[elem.find(lable2[0])::]
20 platdict[key] = value
21 return platdict
22
23 #得到各部分的map24 def getSectionMap(strtmp,lable1 = sectionLable):
25 tmp = strtmp.split(lable1[0])
26 tmp = [elem for elem in tmp if len(elem) > 1]
27 tmp = [elem for elem in tmp if elem.rfind(lable1[1]) > 0]
28 sectionDict = {}
29 for elem in tmp:
30 key = elem[0:elem.find(lable1[1]):]
31 value = elem[elem.find(endlineLable)+len(endlineLable)::]
32 sectionDict[key] = value
33 return sectionDict
34
35 #获取具体配置值36 def getValueMap(strtmp):
37 tmp = strtmp.split(endlineLable)
38 tmp = [elem for elem in tmp if len(elem) > 1]
39 valueDict = {}
40 for elem in tmp:
41 if elem.find(noteLable) > 0: #如果有注释则去掉注释42 elem = elem[0:elem.find(noteLable):]
43 elem = ''.join(elem.split()) #去掉空白字符44 key = elem[0:elem.find(equalLable):]
45 value = elem[elem.find(equalLable)+len(equalLable)::]
46 valueDict[key] = value
47 return valueDict
48
49 f = open(raw_input("Input file name :"),"rb")
50 strFileContent = f.read()
51 f.close()
52 vardict = {}
53
54 var1 = getPlatformMap(strFileContent)
55
56 for k,v in var1.items():
57 var2 = getSectionMap(v)
58 dict3 = {}
59 for k2,v2 in var2.items():
60 var3 = getValueMap(v2)
61 dict3[k2] = var3
62 vardict[k] = dict3
63
64 print vardict["part2"]["global"]["ip"]