python+requests+unittest介面自動化(6):config的使用和封裝
阿新 • • 發佈:2018-12-25
configparser包的使用:
首先是config.ini,也就是configparser包可識別的檔案格式和檔案內容:
格式當然那就是以“.ini”為檔案字尾;內容則是如下:
#filename = config.ini
[url]
urla = https://www.baidu.com
urlb = https://github.com
[detail]
name = tom
name = david
[url]和[detail]在包中被稱作section,中文可以叫“節”,然後裡面以鍵= 值的方式進行賦值。
詳細解釋可以到官網檢視:https://docs.python.org/3/library/configparser.html
以下為讀取config.ini檔案的程式碼:
#總之先匯入
import configparser
#例項化
cf = configparser.ConfirParser()
#傳入檔案路徑,通過read讀取檔案
filepath = "檔案路徑“
content = cf.read(filepath)
#傳入section和key來得到值
value = cf.get(section,key)
#如urla就是:
getUrl = cf.get("url","urla")
以下為寫config.ini檔案的程式碼:
import configparser cf = configparser.ConfigParser() cf.read(filepath) #設定新的值 cf.set(section,key,value) #以寫的許可權,開啟檔案 fp = open(filepath,"w") #通過內建方法寫入值 cf.write(fp) #關閉檔案 fp.close()
但實際使用中,我們會對configparse進行封裝,方便呼叫:
import configparser class ReadConfig(filepath): def __init__(self): self.cf=configparser.ConfigParser() self.cf.read(filepath) def get_value(self, section, key): value = self.cf.get(section,key) return value def set_value(self,section,key,value): self.cf.set(section,key,value) file = open(filepath,"w") self.cf.write(file) file.close()