• Python configparser模块


    1、configparser 模块介绍:一般做自动化测试的时候,会使用到这个模块,用来操作配置文件(ini文件)封装一些常量。比如数据库、邮件、用户名密码、项目常量等等

    2、ini 文件是一种常用配置文件,ini 文件主要如下:

    • ini 文件格式,由节、键、值组成
      • [section]   # 节  
      • key = value   # key:键,value:值
        • 一个配置文件中可以有多个 section,每个 section 名字不能相同,每个 section 下可以分多个键值,每个 section 下的键不能相同;例如:MySQL 配置文件格式为 ini 文件,部分内容如下:
    1. [mysqld_safe]
    2. socket = /var/run/mysqld/mysqld.sock
    3. nice = 0
    4. [mysqld]
    5. user = mysql
    6. pid-file = /var/run/mysqld/mysqld.pid
    7. socket = /var/run/mysqld/mysqld.sock
    8. port = 3306
    9. basedir = /usr
    10. datadir = /var/lib/mysql
    11. tmpdir = /tmp
    12. lc-messages-dir = /usr/share/mysql
    13. bind-address = 127.0.0.1
    14. key_buffer_size = 16M
    15. 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 方法创建,且得到结果如下
    1. import configparser
    2. config = configparser.ConfigParser()
    3. config["DEFAULT"] = {'ServerAliveInterval': '45',
    4. 'Compression': 'yes',
    5. 'CompressionLevel': '9'}
    6. config['bitbucket.org'] = {} # 定义一个节点
    7. config['bitbucket.org']['User'] = 'hg' # 通过字典的添加键值对的方式往节点中添加 keyvalue
    8. config['topsecret.server.com'] = {}
    9. topsecret = config['topsecret.server.com']
    10. topsecret['Host Port'] = '50022' # mutates the parser
    11. topsecret['ForwardX11'] = 'no' # same here
    12. config['DEFAULT']['ForwardX11'] = 'yes'
    13. with open('D:\Evan_duoceshi\my_code_file\practice\configparser_module/conf.ini', 'w') as configfile:
    14. config.write(configfile)
    1. [DEFAULT]
    2. serveraliveinterval = 45
    3. compression = yes
    4. compressionlevel = 9
    5. forwardx11 = yes
    6. [bitbucket.org]
    7. user = hg
    8. [topsecret.server.com]
    9. host port = 50022
    10. 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 
    1. # ini 配置文件内容如下
    2. [DEFAULT]
    3. serveraliveinterval = 45
    4. compression = yes
    5. compressionlevel = 9
    6. forwardx11 = yes
    7. [bitbucket.org]
    8. user = hg
    9. [topsecret.server.com]
    10. host port = 50022
    11. forwardx11 = no
    12. # 获取ini文件section操作
    13. import configparser
    14. cf = configparser.ConfigParser()
    15. cf.read("conf.ini") # 先读取ini文件,才能从ini文件中取数据
    16. print(cf.default_section) # 只能通过default_section拿到ini文件中的DEFAULT节点
    17. print(cf.sections()) # 通过sections可以拿到ini文件中除DEFAULT以外的所有节点
    18. print(cf.defaults()) # 获取到 default 节点中的数据,数据类型是一个有序字典 OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
    19. # 结果如下
    20. DEFAULT
    21. ['bitbucket.org', 'topsecret.server.com']
    22. OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
    1. # 配置文件中的数据
    2. [mysqld_safe]
    3. socket = /var/run/mysqld/mysqld.sock
    4. nice = 0
    5. [mysqld]
    6. user = mysql
    7. pid-file = /var/run/mysqld/mysqld.pid
    8. socket = /var/run/mysqld/mysqld.sock
    9. port = 3306
    10. basedir = /usr
    11. datadir = /var/lib/mysql
    12. tmpdir = /tmp
    13. lc-messages-dir = /usr/share/mysql
    14. bind-address = 127.0.0.1
    15. key_buffer_size = 16M
    16. log_error = /var/log/mysql/error.log 
    17. # Python 读取操作如下
    18. import configparser
    19. #配置文件路径:
    20. path = "C:/Users\Administrator\.PyCharmCE2019.1\config\scratches\scratch.ini"
    21. #创建ConfigParser模块
    22. config = configparser.ConfigParser()
    23. #读取文件
    24. config.read(path, encoding="utf-8")
    25. #获取所有的section
    26. sections = config.sections()
    27. print(sections)
    28. #获取section为mysqld_safe下所有key
    29. keys = config.options("mysqld_safe")
    30. print(keys)
    31. #获取section为mysqld_safe下所有的key-value
    32. items = config.items("mysqld_safe")
    33. print(items)
    34. #获取section为mysqld,key为log_error对应的value
    35. val = config.get("mysqld", "log_error")
    36. print(val)
    37. # 结果如下
    38. ['mysqld_safe', 'mysqld']
    39. ['socket', 'nice']
    40. [('socket', '/var/run/mysqld/mysqld.sock'), ('nice', '0')]
    41. /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 是否存在
    1. import configparser
    2. #配置文件路径
    3. path = "C:/Users\Administrator\.PyCharmCE2019.1\config\scratches\scratch.ini"
    4. #新配置文件
    5. newpath = "C:/Users\Administrator\.PyCharmCE2019.1\config\scratches\scratch1.ini"
    6. #读取配置文件
    7. config = configparser.ConfigParser()
    8. config.read(path)
    9. #是否存在section:mysqld
    10. if not config.has_section("mysqld"):
    11. config.add_section("mysqld")
    12. #设置logerror路径
    13. config.set("mysqld", "log_error", "D:\Evan_duoceshi\my_code_file\practice\configparser_module/mysql_error.log")
    14. #添加section:Mysqldump
    15. if not config.has_section("mysqldump"):
    16. config.add_section("mysqldump")
    17. config.set("mysqld", "max_allowed_packet", "16M")
    18. #打开要写入新的配置文件路径
    19. wf = open(newpath, "w")
    20. #写入文件
    21. config.write(wf, space_around_delimiters=True)
    22. wf.close()
  • 相关阅读:
    leetcode之打家劫舍
    抖音电商商品卡免佣新规落地,商家经营迎来新窗口
    使用el-tree实现懒加载、请求接口的检索依次展开
    克隆他人制定分支代码命令、提交并且提交到本地库命令
    【Python脚本进阶】1.2、python脚本基础知识(中)
    奇数数列求和
    软件工程师备考
    [附源码]计算机毕业设计JAVA基于JSP的美妆购买网站
    网站都变成灰色的了,代码是怎么实现的呢?
    无需公网IP,实现外网远程访问管家婆ERP进销存系统的方法
  • 原文地址:https://blog.csdn.net/Mark_Zhengy/article/details/127669220