Python configparser模塊封裝及構(gòu)造配置文件
1.configparser模塊簡(jiǎn)介
使用配置文件來(lái)靈活的配置一些參數(shù)是一件很常見的事情,配置文件的解析并不復(fù)雜,在python里更是如此,在官方發(fā)布的庫(kù)中就包含有做這件事情的庫(kù),那就是configParser
configParser解析的配置文件的格式比較象ini的配置文件格式,就是文件中由多個(gè)section構(gòu)成,每個(gè)section下又有多個(gè)配置項(xiàng)
2.看一下configparser生成的配置文件的格式
ini配置文件格式如下:
這里是注釋
[log]log_path = base_dir/OutPut/log/[image]img_path = base_dir/OutPut/image/[report]report_path = base_dir/OutPut/report/[test_case]test_case_path = base_dir/TestData/case.xlsx
3.讀取文件內(nèi)容
import configparserimport osimport sysBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))if sys.platform == 'win32': ENV_CONF_DIR = os.path.join(BASE_DIR, ’Common/conf/env_config.ini’).replace(’/’, ’’)else: ENV_CONF_DIR = os.path.join(BASE_DIR, ’Common/conf/env_config.ini’)class Config(object): def __init__(self, path): self.path = path #配置文件名 self.cf = configparser.ConfigParser() #創(chuàng)建一個(gè)配置文件對(duì)象 self.cf.read(self.path, encoding=’utf-8’) # 調(diào)用配置文件對(duì)象的讀取方法,并傳入一個(gè)配置文件名 def get(self, field, key): # 獲取字符串類型的選項(xiàng)值 result = '' try: result = self.cf.get(field, key) except: result = '' return result def set(self, field, key, value): try: self.cf.set(field, key, value) self.cf.write(open(self.path, ’w’))#創(chuàng)建一個(gè)配置文件并將獲取到的配置信息使用配置文件對(duì)象的寫入方法進(jìn)行寫入 except: return False return Truedef r_config(config_file_path, field, key): rf = configparser.ConfigParser() try: rf.read(config_file_path, encoding=’utf-8’) if sys.platform == 'win32': result = rf.get(field, key).replace(’base_dir’, str(BASE_DIR)).replace(’/’, ’’) else: result = rf.get(field, key).replace(’base_dir’, str(BASE_DIR)) except: sys.exit(1) return resultdef w_config(config_file_path, field, key, value): wf = configparser.ConfigParser() try: wf.read(config_file_path) wf.set(field, key, value) wf.write(open(config_file_path, ’w’)) except: sys.exit(1) return Trueif __name__ == ’__main__’: print(r_config(ENV_CONF_DIR, ’log’, ’log_path’)) print(r_config(ENV_CONF_DIR, ’DB’, ’database’))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML入門的常見問(wèn)題(二)2. jsp文件下載功能實(shí)現(xiàn)代碼3. ASP.NET MVC使用異步Action的方法4. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法5. PHP循環(huán)與分支知識(shí)點(diǎn)梳理6. XML入門的常見問(wèn)題(一)7. ASP常用日期格式化函數(shù) FormatDate()8. JSP之表單提交get和post的區(qū)別詳解及實(shí)例9. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享10. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案
