Python使用configparser庫讀取配置文件
這篇文章主要介紹了Python使用configparser庫讀取配置文件,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下
背景:
在寫接口自動化框架,配置數(shù)據(jù)庫連接時,測試環(huán)境和UAT環(huán)境的連接信息不一致,這時可以將連接信息寫到conf或者cfg配置文件中
python環(huán)境請自行準備。
python代碼直接封裝成類,方便其他模塊的引入。
from configparser import ConfigParser
class DoConfig:
def __init__(self,filepath,encoding='utf-8'):
self.cf = ConfigParser()
self.cf.read(filepath,encoding)
#獲取所有的section
def get_sections(self):
return self.cf.sections()
#獲取某一section下的所有option
def get_option(self,section):
return self.cf.options(section)
#獲取section、option下的某一項值-str值
def get_strValue(self,section,option):
return self.cf.get(section,option)
# 獲取section、option下的某一項值-int值
def get_intValue(self, section, option):
return self.cf.getint(section, option)
# 獲取section、option下的某一項值-float值
def get_floatValue(self, section, option):
return self.cf.getfloat(section, option)
# 獲取section、option下的某一項值-bool值
def get_boolValue(self, section, option):
return self.cf.getboolean(section, option)
def setdata(self,section,option,value):
return self.cf.set(section,option,value)
if __name__ == '__main__':
cf = DoConfig('demo.conf')
res = cf.get_sections()
print(res)
res = cf.get_option('db')
print(res)
res = cf.get_strValue('db','db_name')
print(res)
res = cf.get_intValue('db','db_port')
print(res)
res = cf.get_floatValue('user_info','salary')
print(res)
res = cf.get_boolValue('db','is')
print(res)
cf.setdata('db','db_port','3306')
res = cf.get_strValue('db', 'db_port')
print(res)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實現(xiàn)讀取excel文件中所有sheet操作示例
這篇文章主要介紹了python實現(xiàn)讀取excel文件中所有sheet操作,涉及Python基于openpyxl模塊的Excel文件讀取、遍歷相關(guān)操作技巧,需要的朋友可以參考下2019-08-08
Python + OpenCV 實現(xiàn)LBP特征提取的示例代碼
這篇文章主要介紹了Python + OpenCV 實現(xiàn)LBP特征提取的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-07-07
Python采用Django開發(fā)自己的博客系統(tǒng)
這篇文章主要為大家詳細介紹了Python采用Django開發(fā)自己的博客系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-08-08
Python實現(xiàn)HTTP協(xié)議下的文件下載方法總結(jié)
這篇文章主要介紹了Python實現(xiàn)HTTP協(xié)議下的文件下載方法總結(jié),包括端點續(xù)傳下載等功能,需要的朋友可以參考下2016-04-04

