config.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 配置管理器
  5. Configuration Manager
  6. """
  7. from configparser import ConfigParser
  8. import os
  9. import sys
  10. import logging
  11. logger = logging.getLogger(__name__)
  12. class ConfigHandler:
  13. def __init__(self, config_file=None):
  14. self.config = ConfigParser()
  15. # 如果没有指定配置文件,自动查找
  16. if config_file is None:
  17. # 获取当前文件所在目录
  18. current_dir = os.path.dirname(os.path.abspath(__file__))
  19. # 配置文件路径
  20. config_file = os.path.join(current_dir, '..', 'config', 'config.ini')
  21. # 确保路径存在
  22. if os.path.exists(config_file):
  23. self.config.read(config_file, encoding='utf-8')
  24. logger.info(f"✅ 配置文件加载成功: {config_file}")
  25. logger.info(f"加载的节: {self.config.sections()}")
  26. else:
  27. logger.warning(f"⚠️ 配置文件未找到: {config_file}")
  28. def get(self, section, option, default=None):
  29. """获取配置值"""
  30. try:
  31. value = self.config.get(section, option)
  32. # 处理注释
  33. if "#" in value:
  34. value = value.split('#')[0].strip()
  35. # 处理布尔值
  36. if value.lower() in ('true', 'false'):
  37. return value.lower() == 'true'
  38. # 处理数字
  39. if value.isdigit():
  40. return int(value)
  41. # 处理浮点数
  42. try:
  43. return float(value)
  44. except ValueError:
  45. pass
  46. return value
  47. except Exception:
  48. return default
  49. def get_int(self, section, option, default=0):
  50. """获取整数配置值"""
  51. value = self.get(section, option, default)
  52. try:
  53. return int(value)
  54. except (ValueError, TypeError):
  55. return default
  56. def get_bool(self, section, option, default=False):
  57. """获取布尔配置值"""
  58. value = self.get(section, option, default)
  59. if isinstance(value, bool):
  60. return value
  61. if isinstance(value, str):
  62. return value.lower() in ('true', '1', 'yes', 'on')
  63. return default
  64. def get_list(self, section, option, default=None, separator=','):
  65. """获取列表配置值"""
  66. if default is None:
  67. default = []
  68. value = self.get(section, option, '')
  69. if not value:
  70. return default
  71. # 处理 JSON 格式的列表
  72. if value.startswith('[') and value.endswith(']'):
  73. import json
  74. try:
  75. return json.loads(value)
  76. except json.JSONDecodeError:
  77. pass
  78. # 处理逗号分隔的列表
  79. return [item.strip() for item in value.split(separator) if item.strip()]
  80. # 全局配置实例
  81. config_handler = ConfigHandler()