设为首页 加入收藏

TOP

Python参数解析器configparser
2023-07-25 21:28:55 】 浏览:39
Tags:Python 解析器 configparser

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数据类型还原eva l()

import configparser

cf = configparser.ConfigParser()
cf.read("case.config",encoding="utf8")#读取config,有中文注意编码
#value数据类型还原
user = cf["USER"]["user"]
print(type(user))#输出:<class 'str'>
user = eva l(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":"李四"}]

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python unittest数据处理ddt 下一篇Python unittest+ddt+openpyxl

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目