configparser是python自带的配置参数解析器。可以用于解析.config文件中的配置参数。ini文件中由sections(节点)-key-value组成
pip install configparse
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#读取config,有中文注意编码 #获取所有的section sections = cf.sections() print(sections) #输出:['CASE', 'USER']
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#读取config,有中文注意编码 #获取指定section下所有的option options = cf.options("CASE") print(options) #输出:['caseid', 'casetitle', 'casemethod', 'caseexpect']
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')]
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#读取config,有中文注意编码 #获取指定section下指定option的value caseid = cf.get("CASE","caseid") print(caseid)
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#读取config,有中文注意编码 #获取指定section下指定option的value caseid = cf["CASE"]["caseid"] print(caseid) #输出:[1,2,3]
import configparser cf = configparser.ConfigParser() cf.read("case.config",encoding="utf8")#读取config,有中文注意编码 #value数据类型 user = cf["USER"]["user"] print(type(user)) #输出:<class 'str'>
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'>
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":"李四"}]