配置文件读取工具类
| 14 | logger = logging.getLogger(__name__) |
| 15 | |
| 16 | class ConfigReader(object): |
| 17 | """配置文件读取工具类""" |
| 18 | def __init__(self, cfg_string=None, cfg_file=None, interpolation=None, encoding="utf-8-sig"): |
| 19 | """ |
| 20 | 构造函数 |
| 21 | :param cfg_string: ini格式的字符串 |
| 22 | :param cfg_file: ini文件 |
| 23 | :param interpolation: 变量解析方式,默认为None,不解析变量 |
| 24 | :return: |
| 25 | """ |
| 26 | self._cfg = configparser.ConfigParser(interpolation=interpolation) |
| 27 | self._cfg.optionxform = str # 设置key值区分大小写 |
| 28 | self._cfg_string = cfg_string |
| 29 | self._cfg_file = cfg_file |
| 30 | if self._cfg_string: |
| 31 | self._cfg.read_string(self._cfg_string) |
| 32 | else: |
| 33 | self._cfg.read(self._cfg_file, encoding=encoding) |
| 34 | |
| 35 | def read(self, section_name): |
| 36 | """ |
| 37 | 读取ini格式的配置内容 |
| 38 | :param section_name: 需要读取的块名 |
| 39 | :param cfg_string: str, 配置字符串 |
| 40 | :param cfg_file: str, 配置文件路径 |
| 41 | :return: dict, 配置键值对 |
| 42 | """ |
| 43 | rule_params_dict = {} |
| 44 | for key, value in self._cfg.items(section_name): |
| 45 | rule_params_dict[key] = value |
| 46 | return rule_params_dict |
| 47 | |
| 48 | def get_section_names(self): |
| 49 | """ |
| 50 | 获取所有的section名称 |
| 51 | :return: |
| 52 | """ |
| 53 | return self._cfg.sections() |
| 54 | |
| 55 | class ConfigWriter(object): |
| 56 | def write(self, file_path, section_name, section_dict, comment_str=None): |
no outgoing calls
no test coverage detected