utils.py 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. import yaml
  2. import logging
  3. from pathlib import Path
  4. def load_config(config_filename: str = 'config.yml'):
  5. """
  6. 加载位于项目根目录的配置文件。
  7. :param config_filename: 配置文件的名称。
  8. :return: 加载后的配置字典,如果文件未找到则返回空字典。
  9. """
  10. try:
  11. # Path(__file__) -> 获取当前文件 (utils.py) 的路径
  12. # .resolve() -> 将其转换为绝对路径
  13. project_root = Path(__file__).resolve().parent.parent.parent.parent
  14. print(project_root)
  15. # 将项目根目录和配置文件名拼接成完整路径
  16. config_path = project_root / config_filename
  17. logging.info(f"正在从以下路径加载配置: {config_path}")
  18. with open(config_path, 'r', encoding='utf-8') as f:
  19. config = yaml.safe_load(f)
  20. if config is None:
  21. return {}
  22. return config
  23. except FileNotFoundError:
  24. logging.error(f"配置文件在预期的路径未找到: {config_path}")
  25. return {}
  26. except Exception as e:
  27. logging.error(f"加载配置文件时发生错误: {e}")
  28. return {}