config.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 配置管理器
  5. Configuration Manager
  6. """
  7. from configparser import ConfigParser
  8. import os
  9. class ConfigHandler:
  10. def __init__(self, config_file=None):
  11. self.config = ConfigParser()
  12. if os.path.exists(config_file):
  13. self.config.read(config_file, encoding='utf-8-sig')
  14. # @staticmethod
  15. def get(self, section, option, default=None):
  16. try:
  17. value = self.config.get(section, option)
  18. if "#" in value:
  19. value = value.split('#')[0].strip()
  20. except Exception:
  21. value = default
  22. return value
  23. def get_section(self, section):
  24. """获取整个配置段的字典
  25. Args:
  26. section: 配置段名称
  27. Returns:
  28. 该段所有配置的字典,如果不存在则返回空字典
  29. """
  30. try:
  31. if self.config.has_section(section):
  32. return dict(self.config.items(section))
  33. except Exception:
  34. pass
  35. return {}
  36. # 基于 __file__ 解析绝对路径,避免工作目录变化导致找不到配置文件
  37. _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
  38. _config_path = os.path.join(_PROJECT_ROOT, "config", "config.ini")
  39. config_handler = ConfigHandler(_config_path)