1.configparser介紹
configparser是python自帶的配置引數決議器,可以用于決議.config檔案中的配置引數,ini檔案中由sections(節點)-key-value組成

2.安裝:
pip install configparse
3.獲取所有的section
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼 #獲取所有的section sections = cf.sections() print(sections) #輸出:['CASE', 'USER']
4.獲取指定section下的option
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼 #獲取指定section下所有的option options = cf.options("CASE") print(options) #輸出:['caseid', 'casetitle', 'casemethod', 'caseexpect']
5.獲取指定section的K-V
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼#獲取指定section下的option和value,每一個option作為一個元祖[(),(),()] alls = cf.items("CASE") print(alls) #輸出:[('caseid', '[1,2,3]'), ('casetitle', '["正確登陸","密碼錯誤"]'), ('casemethod', '["get","post","put"]'), ('caseexpect', '0000')]
6.獲取指定value(1)
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼 #獲取指定section下指定option的value caseid = cf.get("CASE","caseid") print(caseid)
7.獲取指定value(2)
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼 #獲取指定section下指定option的value caseid = cf["CASE"]["caseid"] print(caseid) #輸出:[1,2,3]
8.value資料型別
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼 #value資料型別 user = cf["USER"]["user"] print(type(user)) #輸出:<class 'str'>
9.value資料型別還原eval()
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#讀取config,有中文注意編碼 #value資料型別還原 user = cf["USER"]["user"] print(type(user))#輸出:<class 'str'> user = eval(user) print(type(user))#輸出:<class 'list'>
10.封裝
import configparser class GetConfig(): def get_config_data(self,file,section,option): cf = configparser.ConfigParser() cf.read(file, encoding="utf8") # 讀取config,有中文注意編碼 # 回傳value return cf[section][option] if __name__ == '__main__': values = GetConfig().get_config_data("case.config","USER","user") print(values) #輸出:[{"username":"張三","password":"123456"},{"username":"李四"}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540366.html
標籤:其他
上一篇:Python unittest+ddt+openpyxl
下一篇:pandas替換,加載,透視表

