| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 配置管理器
- Configuration Manager
- """
- from configparser import ConfigParser
- import os
- import sys
- import logging
- logger = logging.getLogger(__name__)
- class ConfigHandler:
- def __init__(self, config_file=None):
- self.config = ConfigParser()
-
- # 如果没有指定配置文件,自动查找
- if config_file is None:
- # 获取当前文件所在目录
- current_dir = os.path.dirname(os.path.abspath(__file__))
- # 配置文件路径
- config_file = os.path.join(current_dir, '..', 'config', 'config.ini')
-
- # 确保路径存在
- if os.path.exists(config_file):
- self.config.read(config_file, encoding='utf-8')
- logger.info(f"✅ 配置文件加载成功: {config_file}")
- logger.info(f"加载的节: {self.config.sections()}")
- else:
- logger.warning(f"⚠️ 配置文件未找到: {config_file}")
-
- def get(self, section, option, default=None):
- """获取配置值"""
- try:
- value = self.config.get(section, option)
- # 处理注释
- if "#" in value:
- value = value.split('#')[0].strip()
- # 处理布尔值
- if value.lower() in ('true', 'false'):
- return value.lower() == 'true'
- # 处理数字
- if value.isdigit():
- return int(value)
- # 处理浮点数
- try:
- return float(value)
- except ValueError:
- pass
- return value
- except Exception:
- return default
-
- def get_int(self, section, option, default=0):
- """获取整数配置值"""
- value = self.get(section, option, default)
- try:
- return int(value)
- except (ValueError, TypeError):
- return default
-
- def get_bool(self, section, option, default=False):
- """获取布尔配置值"""
- value = self.get(section, option, default)
- if isinstance(value, bool):
- return value
- if isinstance(value, str):
- return value.lower() in ('true', '1', 'yes', 'on')
- return default
-
- def get_list(self, section, option, default=None, separator=','):
- """获取列表配置值"""
- if default is None:
- default = []
- value = self.get(section, option, '')
- if not value:
- return default
- # 处理 JSON 格式的列表
- if value.startswith('[') and value.endswith(']'):
- import json
- try:
- return json.loads(value)
- except json.JSONDecodeError:
- pass
- # 处理逗号分隔的列表
- return [item.strip() for item in value.split(separator) if item.strip()]
- # 全局配置实例
- config_handler = ConfigHandler()
|