因為項目的需要,要用到Python加載配置文件。本文主要參考了http://www.cnblogs.com/victorwu/p/5762931.html
a) 配置文件中包含一個或多個 section, 每個 section 有自己的 option;
b) section 用 [sect_name] 表示,每個option是一個鍵值對,使用分隔符 = 或 : 隔開;
c) 在 option 分隔符兩端的空格會被忽略掉
d) 配置文件使用 # 和 ; 注釋
下面給出一個配置文件的例子。
[mongodb]host = amaster[kafka]bootstrap_servers = amaster:9092,anode1:9092,anode2:9092[log]log_file_name = kuaidaili_spider.log[zookeeper]conn_str = amaster:2181,anode1:2181,anode2:2181測試代碼:
#-*- coding: utf-8 -*-import ConfigParserdef func(): cp = ConfigParser.SafeConfigParser() cp.read('kuaidaili_spider.cfg') 輸出結果:mongodb host amasterkafka bootstrap_servers amaster:9092,anode1:9092,anode2:9092log file name kuaidaili_spider.logzookeeper conn string amaster:2181,anode1:2181,anode2:2181下面的內容來自http://www.cnblogs.com/victorwu/p/5762931.html
配置文件如果包含 Unicode 編碼的數據,需要使用 codecs 模塊以合適的編碼打開配置文件。
myapp.conf
[msg]hello = 你好config_parser_unicode.pyimport ConfigParserimport codecscp = ConfigParser.SafeConfigParser()with codecs.open('myapp.conf', 'r', encoding='utf-8') as f: cp.readfp(f)print cp.get('msg', 'hello')通常情況下, option 是一個鍵值對。但是,當 SafeConfigParser 的參數 allow_no_value 設置成 True 時,它允許 option 不設置值而只是作為一個標識。
allow_no_value.conf
# option as Flag[flag]flag_optallow_no_value.py
import ConfigParsercp = ConfigParser.SafeConfigParser(allow_no_value = True)cp.read('myapp.conf')print cp.get('flag', 'flag_opt'); # Noneallow_no_value 默認設置成 False,此時如果配置文件中存在沒有設置值的 option,在讀取配置文件時將拋出異常
ConfigParser.ParsingError。當 allow_no_value 設置成 True 時,如果一個 option 沒有設置值,has_option 方法會返回 True,get 方法會返回 None。
如果配置文件中存在一個名為 DEFAULT 的 section,那么其他 section 會擴展它的 option 并且可以覆蓋它的 option。
db.conf
[DEFAULT]host = 127.0.0.1port = 3306[db_root]user = rootpass = root[db_huey]host = 192.168.1.101user = hueypass = hueydefault_section.py
print cp.get('db_root', 'host') # 127.0.0.1print cp.get('db_huey', 'host') # 192.168.1.101SafeConfigParser 提供了插值的特性來結合數據。
url.conf
[DEFAULT]url = %(protocol)s://%(server)s:%(port)s/[http]protocol = httpserver = localhostport = 8080[ftp]url = %(protocol)s://%(server)s/protocol = ftpserver = 192.168.1.102interpolation_demo.py
import ConfigParsercp = ConfigParser.SafeConfigParser()cp.read('url.conf')print cp.get('http', 'url') # http://localhost:8080/print cp.get('ftp', 'url') # ftp://192.168.1.102/新聞熱點
疑難解答