Python参数解析器configparser简介

2022-12-23,

configparser是python自带的配置参数解析器,可以用于解析.config文件中的配置参数,ini文件中由sections(节点)-key-value组成,这篇文章主要介绍了Python参数解析器configparser,需要的朋友可以参考下

目录
  • 1.configparser介绍
  • 2.安装:
  • 3.获取所有的section
  • 4.获取指定section下的option
  • 5.获取指定section的K-V
  • 6.获取指定value(1)
  • 7.获取指定value(2)
  • 8.value数据类型
  • 9.value数据类型还原eval()
  • 10.封装

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

到此这篇关于Python参数解析器configparser的文章就介绍到这了,更多相关Python参数解析器内容请搜索北冥有鱼以前的文章或继续浏览下面的相关文章希望大家以后多多支持北冥有鱼!

《Python参数解析器configparser简介.doc》

下载本文的Word格式文档,以方便收藏与打印。