不少時候須要從配置文件中讀取參數,在程序中使用,這時候就須要用到ConfigParser模塊(在Python3以上的版本中爲configparser模塊)
首先新建一個配置文件樣例:myapp.confpython
# database source [db] host = 127.0.0.1 port = 3306 user = root pass = root # ssh [ssh] host = 192.168.1.101 user = huey pass = huey
在Python代碼中:app
#實例化 ConfigParser 並加載配置文件 cp = ConfigParser.SafeConfigParser() cp.read('myapp.conf') #獲取 section 列表、option 鍵列表和 option 鍵值元組列表 print 'all sections:', cp.sections() # sections: ['db', 'ssh'] print 'options of [db]:', cp.options('db') # options of [db]: ['host', 'port', 'user', 'pass'] print 'items of [ssh]:', cp.items('ssh') # items of [ssh]: [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')] #讀取指定的配置信息 print 'host of db:', cp.get('db', 'host') # host of db: 127.0.0.1 print 'host of ssh:', cp.get('ssh', 'host') # host of ssh: 192.168.1.101 #按類型讀取配置信息:getint、 getfloat 和 getboolean print type(cp.getint('db', 'port')) # <type 'int'> #判斷 option 是否存在 print cp.has_option('db', 'host') # True #設置 option cp.set('db', 'host','192.168.1.102') #刪除 option cp.remove_option('db', 'host') #判斷 section 是否存在 print cp.has_section('db') # True #添加 section cp.add_section('new_sect') #刪除 section cp.remove_section('db') #保存配置,set、 remove_option、 add_section 和 remove_section 等操做並不會修改配置文件,write 方法能夠將 ConfigParser 對象的配置寫到文件中 cp.write(open('myapp.conf', 'w')) cp.write(sys.stdout)
若是配置文件中有中文等字符,能夠使用codecs讀取文件ssh
import ConfigParser import codecs cp = ConfigParser.SafeConfigParser() with codecs.open('myapp.conf', 'r', encoding='utf-8') as f: cp.readfp(f)
DEFAULT sectioncode
[DEFAULT] host = 127.0.0.1 port = 3306 [db_root] user = root pass = root [db_huey] host = 192.168.1.101 user = huey pass = huey ------------------------- print cp.get('db_root', 'host') # 127.0.0.1 print cp.get('db_huey', 'host') # 192.168.1.101
存在的問題:
ConfigParser的一些問題:對象
易用性
綜合上述ConfigParse的一些問題,若是在使用時,不須要寫回, 仍是ConfigParser 更易用一些, 只要注意配置文件的參數儘可能使用小寫便可; 不然, 建議使用configobj。
注意事項
配置參數讀出來都是字符串類型, 參數運算時,注意類型轉換,另外,對於字符型參數,不須要加引號utf-8