Python使用configparser库封装配置读取类

巷口听风
巷口听风
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍如何利用Python内置的configparser库封装一个配置读取类,解决接口自动化框架中多环境数据库连接信息不一致的问题。通过示例展示了如何获取Section、Option及各类数据值,并支持配置修改与保存,便于其他模块直接调用。

本文详细讲解如何在Python中利用configparser库来读取配置文件,并通过示例代码展示具体实现方式,为相关学习或工作提供参考。

配置读取类封装实现

背景说明:

在开发接口自动化框架时,测试环境与UAT环境的数据库连接信息往往存在差异。此时,将连接配置写入conf或cfg文件中是常见的解决方案。

请确保已准备好相应的Python运行环境。

为便于其他模块调用,建议将Python代码封装为类形式。

代码示例与测试


from configparser import ConfigParser

class DoConfig:
  def __init__(self,filepath,encoding='utf-8'):
    self.cf = ConfigParser()
    self.cf.read(filepath,encoding)

  #获取所有的section
  def get_sections(self):
    return self.cf.sections()

  #获取某一section下的所有option
  def get_option(self,section):
    return self.cf.options(section)

  #获取section、option下的某一项值-str值
  def get_strValue(self,section,option):
    return self.cf.get(section,option)

  # 获取section、option下的某一项值-int值
  def get_intValue(self, section, option):
    return self.cf.getint(section, option)

  # 获取section、option下的某一项值-float值
  def get_floatValue(self, section, option):
    return self.cf.getfloat(section, option)

  # 获取section、option下的某一项值-bool值
  def get_boolValue(self, section, option):
    return self.cf.getboolean(section, option)

  def setdata(self,section,option,value):
    return self.cf.set(section,option,value)

if __name__ == '__main__':
  cf = DoConfig('demo.conf')
  res = cf.get_sections()
  print(res)
  res = cf.get_option('db')
  print(res)
  res = cf.get_strValue('db','db_name')
  print(res)
  res = cf.get_intValue('db','db_port')
  print(res)
  res = cf.get_floatValue('user_info','salary')
  print(res)
  res = cf.get_boolValue('db','is')
  print(res)

  cf.setdata('db','db_port','3306')
  res = cf.get_strValue('db', 'db_port')
  print(res)

以上即为本文的全部内容,希望能为各位的学习带来帮助,欢迎继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表