config.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import yaml
  2. import os
  3. class Config:
  4. def __init__(self, filename="config.yaml"):
  5. self.filename = filename
  6. self.config = self.load()
  7. def load(self):
  8. # 获取config.py文件所在的目录
  9. config_dir = os.path.dirname(os.path.abspath(__file__))
  10. # 构建配置文件的完整路径
  11. config_path = os.path.join(config_dir, self.filename)
  12. # 检查配置文件是否存在
  13. if not os.path.exists(config_path):
  14. raise FileNotFoundError(f"配置文件 {config_path} 未找到")
  15. with open(config_path, 'r', encoding="utf-8") as f:
  16. self.config = yaml.safe_load(f)
  17. return self.config
  18. def get(self, key):
  19. """
  20. 传入键返回值,如果有格式嵌套用 . 拼凑
  21. 如: app_id = config.get("bot.app_id")
  22. """
  23. keys = key.split(".")
  24. if len(keys) == 1:
  25. return self.config.get(keys[0])
  26. conf = self.config
  27. for k in keys:
  28. conf = conf.get(k)
  29. return conf
  30. config = Config()
  31. if __name__ == "__main__":
  32. config = Config()
  33. print(config.get("bot.app_id"))