在程式中使用設定檔來靈活的配置一些參數是一件很常見的事情,設定檔的解析並不複雜,在python裡更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是ConfigParser,這裡簡單的做一些介紹。
ConfigParser解析的設定檔的格式比較象ini的設定檔格式,就是檔案中由多個section構成,每個section下又有多個配置項,比如:
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
假設上面的設定檔的名字為test.conf。裡麵包含兩個section,一個是db, 另一個是concurrent, db裡面還包含有4項,concurrent裡面有兩項。這裡來做做解析:
#-*- encoding: gb2312 -*-
import ConfigParser
import string, os, sys
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
# 返回所有的section
s = cf.sections()
print 'section:', s
o = cf.options("db")
print 'options:', o
v = cf.items("db")
print 'db:', v
print '-'*60
#可以按照類型讀取出來
db_host = cf.get("db", "db_host")
db_port = cf.getint("db", "db_port")
db_user = cf.get("db", "db_user")
db_pass = cf.get("db", "db_pass")
# 返回的是整型的
threads = cf.getint("concurrent", "thread")
processors = cf.getint("concurrent", "processor")
print "db_host:", db_host
print "db_port:", db_port
print "db_user:", db_user
print "db_pass:", db_pass
print "thread:", threads
print "processor:", processors
#修改一個值,再寫回去
cf.set("db", "db_pass", "zhaowei")
cf.write(open("test.conf", "w"))