#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 配置管理器 Configuration Manager """ from configparser import ConfigParser import os class ConfigHandler: def __init__(self, config_file=None): self.config = ConfigParser() if os.path.exists(config_file): self.config.read(config_file, encoding='utf-8-sig') # @staticmethod def get(self, section, option, default=None): try: value = self.config.get(section, option) if "#" in value: value = value.split('#')[0].strip() except Exception: value = default return value def get_section(self, section): """获取整个配置段的字典 Args: section: 配置段名称 Returns: 该段所有配置的字典,如果不存在则返回空字典 """ try: if self.config.has_section(section): return dict(self.config.items(section)) except Exception: pass return {} # 基于 __file__ 解析绝对路径,避免工作目录变化导致找不到配置文件 _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) _config_path = os.path.join(_PROJECT_ROOT, "config", "config.ini") config_handler = ConfigHandler(_config_path)