Python configparser模块
1、configparser 模块介绍:一般做自动化测试的时候,会使用到这个模块,用来操作配置文件(ini文件)封装一些常量。比如数据库、邮件、用户名密码、项目常量等等
2、ini 文件是一种常用配置文件,ini 文件主要如下:
- ini 文件格式,由节、键、值组成
- [section] # 节
- key = value # key:键,value:值
-
- 一个配置文件中可以有多个 section,每个 section 名字不能相同,每个 section 下可以分多个键值,每个 section 下的键不能相同;例如:MySQL 配置文件格式为 ini 文件,部分内容如下:
[mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp lc-messages-dir = /usr/share/mysql bind-address = 127.0.0.1 key_buffer_size = 16M log_error = /var/log/mysql/error.log
- ini 文件创建
- 在 Pycharm 编辑器中,如果右击 new scratch file 中没有 ini 文件选项,则需要安装插件,步骤如下
- Pycharm 点击 File 选择 setting 选项
- 进入 Plugins 在 Marketplace 中找到 Ini 插件点击安装,然后重启 Pycharm
- 再次进入 new scratch file 中就能找到 ini 文件
- 通过 open 方法创建,且得到结果如下
- 在 Pycharm 编辑器中,如果右击 new scratch file 中没有 ini 文件选项,则需要安装插件,步骤如下
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} # 定义一个节点 config['bitbucket.org']['User'] = 'hg' # 通过字典的添加键值对的方式往节点中添加 key 和 value config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('D:\Evan_duoceshi\my_code_file\practice\configparser_module/conf.ini', 'w') as configfile: config.write(configfile)
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
- ini 文件读取操作,ini 文件需要通过 configparser 模块操作,configparser 是 Python 中自带模块,方法操作如下
- config = configparser.ConfigParser() 创建 ConfigParser 对象
- config.read(filenames, encoding=None) 读取配置文件
- config.sections() 获取所有的 section,除 default 节点外
- config.default_section 只能获取 default 节点的 section
- config.options(section) 获取指定 section 下所有的 key
- config.get(section, option,…) 获取指定 section 下指定 key 的值
- config.items(section,…) 获取指定 section 下所有 key 与 value
# ini 配置文件内容如下 [DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no # 获取ini文件section操作 import configparser cf = configparser.ConfigParser() cf.read("conf.ini") # 先读取ini文件,才能从ini文件中取数据 print(cf.default_section) # 只能通过default_section拿到ini文件中的DEFAULT节点 print(cf.sections()) # 通过sections可以拿到ini文件中除DEFAULT以外的所有节点 print(cf.defaults()) # 获取到 default 节点中的数据,数据类型是一个有序字典 OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')]) # 结果如下 DEFAULT ['bitbucket.org', 'topsecret.server.com'] OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
# 配置文件中的数据 [mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp lc-messages-dir = /usr/share/mysql bind-address = 127.0.0.1 key_buffer_size = 16M log_error = /var/log/mysql/error.log # Python 读取操作如下 import configparser #配置文件路径: path = "C:/Users\Administrator\.PyCharmCE2019.1\config\scratches\scratch.ini" #创建ConfigParser模块 config = configparser.ConfigParser() #读取文件 config.read(path, encoding="utf-8") #获取所有的section sections = config.sections() print(sections) #获取section为mysqld_safe下所有key keys = config.options("mysqld_safe") print(keys) #获取section为mysqld_safe下所有的key-value items = config.items("mysqld_safe") print(items) #获取section为mysqld,key为log_error对应的value val = config.get("mysqld", "log_error") print(val) # 结果如下 ['mysqld_safe', 'mysqld'] ['socket', 'nice'] [('socket', '/var/run/mysqld/mysqld.sock'), ('nice', '0')] /var/log/mysql/error.log
- ini 文件修改操作
- config.set(section, option, value=None) 设置 section 中指定 key 的 value 值,key 不存在,直接添加 key-value
- config.add_section(section) 配置信息中添加 section
- config.remove_section(section) 删除 section
- config.remove_option 删除指定 section 中 key
- config.write(fp, space_around_delimiters=True) 所有修改 ini 配置文件的操作后都需要执行写入操作,将配置信息写回到配置文件
- 检查 section 与 key 的方法:
- config.has_section(section) 检查指定 section 是否存在
- config.has_option(section, option) 检查指定 section 下 option 是否存在
import configparser #配置文件路径 path = "C:/Users\Administrator\.PyCharmCE2019.1\config\scratches\scratch.ini" #新配置文件 newpath = "C:/Users\Administrator\.PyCharmCE2019.1\config\scratches\scratch1.ini" #读取配置文件 config = configparser.ConfigParser() config.read(path) #是否存在section:mysqld if not config.has_section("mysqld"): config.add_section("mysqld") #设置logerror路径 config.set("mysqld", "log_error", "D:\Evan_duoceshi\my_code_file\practice\configparser_module/mysql_error.log") #添加section:Mysqldump if not config.has_section("mysqldump"): config.add_section("mysqldump") config.set("mysqld", "max_allowed_packet", "16M") #打开要写入新的配置文件路径 wf = open(newpath, "w") #写入文件 config.write(wf, space_around_delimiters=True) wf.close()
作者:Evan0813
微信:ZhengYing8887
出处:https://www.cnblogs.com/ZhengYing0813/
备注:本文版权归作者所有,欢迎转载和添加作者微信探讨技术,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号