日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python參數解析器configparser簡介_python

作者:味卜鮮碼 ? 更新時間: 2023-01-21 編程語言

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.cnblogs.com/QAbujiaban/p/16995421.html

欄目分類
最近更新