用python讀取設定檔比較方便,比如下面一個設定檔:
0.ini檔案:
---------------檔案開始----------------
[global]
ip = 192.168.1.100 ;ip地址
port = 1234
MAC = 0x414243444546;mac
---------------檔案結束----------------
要從中讀取ip地址我們可以用如下代碼:
1 #! /usr/bin/python
2 #-*- 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檔案:
---------------檔案開始----------------
# 設定檔
<part1>
[global] #全域配置參數
ip = 192.168.1.100
port = 1234
MAC = 0x414243444546# MAC地址
<part2>
[global] #全域配置參數
ip = 192.168.1.101
port = 1234
MAC = 0x414243444547 # MAC地址
---------------檔案結束----------------
對於擴充的設定檔格式,上述代碼不能解析。預設的配置有時候局限太大,用起來不太方便。
我們可以藉助python的dict資料結構完成設定檔的解析,使用起來也很方便。
下面是個樣本,可以讀取上述擴充的設定檔。
讀取程式碼範例:
1 #! /usr/bin/python
2 #-*- coding: utf-8 -*-
3
4 partLable = ("<",">")
5 sectionLable = ("[","]")
6 endlineLable = "\r\n" # windows下的行標誌
7 #endlineLable = "\n" # linux下的行標誌
8 equalLable = "=" # 賦值標誌
9 noteLable = '#' # 注釋標誌
10
11 # 得到總配置的map
12 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 # 得到各部分的map
24 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"]
這裡只提供一種思路,並驗證其可行性,具體實施可以藉助C++等其它語言改寫以滿足需求。