Python参数解析器configparser,可以用于解析.con


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":"李四"}]

 

评论关闭