path_utils.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os
  2. import sys
  3. def find_project_root(marker: str = ".env") -> str:
  4. """
  5. 查找项目根目录。它通过向上搜索一个标记文件(如 '.env'、'.git'、'pyproject.toml')来工作。
  6. :param marker: 用于识别项目根目录的标记文件或目录名。
  7. :return: 项目根目录的绝对路径。
  8. :raises FileNotFoundError: 如果找不到任何标记文件,意味着项目结构可能不标准。
  9. """
  10. current_path = os.path.abspath(__file__) # 获取当前文件的绝对路径
  11. while True:
  12. if os.path.exists(os.path.join(current_path, marker)):
  13. # 找到了标记文件,当前目录即为项目根目录
  14. return current_path
  15. parent_path = os.path.dirname(current_path)
  16. if parent_path == current_path:
  17. error_msg = f"项目根目录标记文件 '{marker}' 未在任何父目录中找到,从 {os.path.abspath(__file__)} 向上查找。"
  18. raise FileNotFoundError(error_msg)
  19. current_path = parent_path # 继续向上级目录搜索
  20. # 项目根目录
  21. project_root = find_project_root()
  22. # 配置路径
  23. config_dir = os.path.join(project_root, "config")
  24. spiders_config_path = os.path.join(config_dir, "spiders_config.yaml")
  25. # 日志路径
  26. log_dir = os.path.join(project_root, "logs")
  27. os.makedirs(log_dir, exist_ok=True)
  28. __all__ = [
  29. "project_root",
  30. "config_dir",
  31. "spiders_config_path",
  32. "log_dir",
  33. "get_project_path"
  34. ]
  35. def get_project_path() -> str:
  36. """
  37. 获取 AutoScraperX 项目根路径
  38. 支持从任何子模块中调用而不会路径错乱
  39. """
  40. return project_root