config.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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')
  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. # 全局配置实例
  37. config_handler = ConfigHandler("./config/config.ini")