解析配置檔案ConfigParser模組

2021-06-26 08:39:04 字數 2905 閱讀 8092

**:

配置檔案內容:

[plain]view plain

copy

[db]  

db_host=127.0.0.1  

db_port=3306  

db_user=root  

db_pass=password  

[concurrent]  

thread=10  

processor=20  

如果遵循以上格式,那麼就可以用python的configparser模組。

[python]view plain

copy

#!/usr/bin/python

# filename: parse_module.py

import

configparser  

filename = 'my.conf'

parse = configparser.configparser()  

parse.read(filename)  

sections = parse.sections()  

fori 

insections:  

options = parse.options(i)  

values = parse.items(i)  

print

"section is %s "

% i  

print

"options are %s "

% options  

print

"values are %s "

% values  

輸出:[plain]view plain

copy

section is db   

options are ['db_host', 'db_port', 'db_user', 'db_pass']   

values are [('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')]   

section is concurrent   

options are ['thread', 'processor']   

values are [('thread', '10'), ('processor', '20')]   

但是如果配置檔案中,parameter選項中含有,則無法用此模組進行解析。。因此當試用python作為開發語言時,配置檔案的格式可以選擇符合configparser模組的格式。。。

下面的配置就無法使用configparser模組. 會將含有的部分當作section來解析。。。。

[plain]view plain

copy

[db]  

host[0]=127.0.0.1  

host[1] = 192.168.1.123  

db_port=3306  

db_user=root  

db_pass=password  

[concurrent]  

thread=10  

processor=20  

使用configparser模組解析配置檔案時,發現的問題:

引數名稱的大寫全部會轉換為小寫。

引數名稱不能含有[,]

如果含有多個名字相同的section時,會以最後乙個section為準。

乙個簡單的讀配置檔案的**,其中section部分相當與忽略了,而返回乙個包含所有的引數的dict。

[python]view plain

copy

#!/usr/bin/python

# filename: readconf.py

import

configparser  

cofile = 'test2.properties'

defread_config_file(filename):  

'''''read_config_file(filename)

this function is used for parse the config file'''

data = {}  

config = configparser.configparser()  

try:  

with open(filename,'r'

) as confile:  

config.readfp(confile)  

#config.read(filename)

fori 

inconfig.sections():  

for(key, value) 

inconfig.items(i):  

data[key] = value  

return

data      

except

exception:  

print

"open file error."

p = read_config_file(cofile)  

還是發現了乙個問題,如果不同的section中含有相同引數名字的引數,那個上面這個解析將無法判斷出引數來自哪個section。

例如,myslq的配置檔案中,client section和mysqld section中都含有socket和port這兩個引數。如果用上面的**,則無法判斷哪個dict中的兩個socket和port分別來自哪個section。。。

這樣存放了之後,dict中的元素的先後順序,和新增的順序有不同。

配置檔案解析函式

config.h this file is usred for parsing configure file.e mail yhniejun 163.com 2007.01.25 mr.nie the struct of config file.struct conf info typedef st...

tinyxml解析配置檔案

一 tinyxml類簡單介紹 tinyxml實現的時dom訪問模型,因此提供了一系列的類對應xml檔案中的各個節點。主要類間的關係如下圖所示 tixmlbase 其他類的基類,是個抽象類 tixmldocument 表示整個xml文件,不對應其中某個特定的節點。tixmlelement 表示元素節點...

DOM解析配置檔案

config.php header content type text html charset utf 8 doc new domdocument 1.0 utf 8 doc load config.xml 第一步獲得documentelement跟元素 config doc documentel...