""" 配置管理器 - 封装配置的全局访问 """ import configparser from pathlib import Path from typing import Any, Optional class ConfigManager: """配置管理器单例类""" _instance: Optional['ConfigManager'] = None _config: Optional[configparser.ConfigParser] = None _config_file: str = "config.ini" def __new__(cls) -> 'ConfigManager': if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): if self._config is None: self._config = configparser.ConfigParser() self._load_config() def _load_config(self) -> None: """加载配置文件""" config_path = Path(self._config_file) if config_path.exists(): self._config.read(self._config_file, encoding='utf-8') def reload(self) -> None: """重新加载配置""" self._config = configparser.ConfigParser() self._load_config() def save(self) -> None: """保存配置到文件""" with open(self._config_file, 'w', encoding='utf-8') as f: self._config.write(f) def get(self, section: str, option: str, fallback: str = '') -> str: """获取配置值""" return self._config.get(section, option, fallback=fallback) def get_int(self, section: str, option: str, fallback: int = 0) -> int: """获取整数配置值""" return self._config.getint(section, option, fallback=fallback) def get_float(self, section: str, option: str, fallback: float = 0.0) -> float: """获取浮点数配置值""" return self._config.getfloat(section, option, fallback=fallback) def get_bool(self, section: str, option: str, fallback: bool = False) -> bool: """获取布尔配置值""" return self._config.getboolean(section, option, fallback=fallback) def set(self, section: str, option: str, value: Any) -> None: """设置配置值""" if not self._config.has_section(section): self._config.add_section(section) self._config.set(section, option, str(value)) def get_section(self, section: str) -> configparser.SectionProxy: """获取整个配置节""" return self._config[section] def has_section(self, section: str) -> bool: """检查配置节是否存在""" return self._config.has_section(section) def has_option(self, section: str, option: str) -> bool: """检查配置项是否存在""" return self._config.has_option(section, option) @property def config(self) -> configparser.ConfigParser: """获取原始配置对象""" return self._config def update_from_dict(self, config_dict: dict) -> None: """从字典更新配置""" for section, options in config_dict.items(): if not self._config.has_section(section): self._config.add_section(section) for option, value in options.items(): self._config.set(section, option, str(value)) # 全局配置管理器实例 config_manager = ConfigManager() def get_config() -> configparser.ConfigParser: """获取配置对象(向后兼容)""" return config_manager.config def save_config_file(config: configparser.ConfigParser) -> None: """保存配置文件(向后兼容)""" config_manager._config = config config_manager.save()