标签:sig 实现 代码 use bsp 示例 code option param
[server] age = 45 username = yes # server就是section # age、username就是option
1 import configparser 2 3 filename = ‘F:/Interface/config/server.ini‘ 4 # 实例化configparser 5 config = configparser.ConfigParser() 6 7 # 读取配置文件 8 config.read(filename, encoding="utf-8-sig") 9 10 # 获取某个option的值(最常见的操作) 11 config.get(section="server", option="username")
为了更好的复用configparser,我们将常用的方法写成一个封装类
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 """ 5 __title__ = 操作配置文件工具类 6 """ 7 8 import configparser 9 10 11 class ConfigUtil: 12 # 实例化configparser 13 config = configparser.ConfigParser() 14 15 def read(self, filename): 16 """ 17 读取配置文件 18 :param filename: 配置文件路径 19 """ 20 self.config.read(filename, encoding="utf-8-sig") 21 22 def get(self, _options, _section=‘server‘): 23 """ 24 获取某个options值 25 :param _options: option 26 :param _section: section 27 """ 28 try: 29 # 方式一:调用方法 30 value = self.config.get(section=_section, option=_options, fallback="默认值,key不存在则返回此值") 31 32 # 方式二:索引 33 value = self.config[_section][_options] 34 except Exception as e: 35 print("没有获取到值") 36 value = None 37 return value 38 39 def get_options_key_value(self, _section): 40 """ 41 以列表(name,value)的形式返回section中的每个值 42 :param _section: 某个section 43 :return: list[tuple(key,value)] 44 """ 45 return self.config.items(_section) 46 47 def get_all_section(self): 48 """ 49 获取所有section 50 """ 51 return self.config.sections() 52 53 def get_options_by_section(self, _section): 54 """ 55 获取section下所有可用options 56 """ 57 # 方式一 58 keys = [] 59 for _options in self.config[_section]: 60 keys.append(_options) 61 62 # 方式二(推荐) 63 keys = self.config.options(_section) 64 return keys 65 66 def assert_section_in_config(self, _section): 67 """ 68 判断section是否存在 69 :param _section: 需要判断的section 70 """ 71 return _section in self.config 72 73 def assert_options_in_section(self, _section, _options): 74 """ 75 判断options是否存在某个section中 76 :param _section: 某个section 77 :param _options: 需要判断的options的key值 78 """ 79 return _options in self.config[_section] 80 81 82 configUtil = ConfigUtil() 83 84 if __name__ == ‘__main__‘: 85 filename = ‘F:/imocInterface/config/server.ini‘ 86 configUtil.read(filename) 87 print(configUtil.get("username")) 88 print(configUtil.get_all_section()) 89 print(configUtil.assert_section_in_config("server")) 90 print(configUtil.get_options_by_section("server")) 91 print(configUtil.assert_options_in_section("server", "usernsame")) 92 print(configUtil.get_options_key_value("server"))
python接口自动化测试 - configparser配置文件解析器详细使用
标签:sig 实现 代码 use bsp 示例 code option param
原文地址:https://www.cnblogs.com/poloyy/p/12244936.html