12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- import os
- import sys
- def find_project_root(marker: str = ".env") -> str:
- """
- 查找项目根目录。它通过向上搜索一个标记文件(如 '.env'、'.git'、'pyproject.toml')来工作。
- :param marker: 用于识别项目根目录的标记文件或目录名。
- :return: 项目根目录的绝对路径。
- :raises FileNotFoundError: 如果找不到任何标记文件,意味着项目结构可能不标准。
- """
- current_path = os.path.abspath(__file__) # 获取当前文件的绝对路径
- while True:
- if os.path.exists(os.path.join(current_path, marker)):
- # 找到了标记文件,当前目录即为项目根目录
- return current_path
- parent_path = os.path.dirname(current_path)
- if parent_path == current_path:
- error_msg = f"项目根目录标记文件 '{marker}' 未在任何父目录中找到,从 {os.path.abspath(__file__)} 向上查找。"
- raise FileNotFoundError(error_msg)
- current_path = parent_path # 继续向上级目录搜索
- # 项目根目录
- project_root = find_project_root()
- # 配置路径
- config_dir = os.path.join(project_root, "config")
- spiders_config_path = os.path.join(config_dir, "spiders_config.yaml")
- # 日志路径
- log_dir = os.path.join(project_root, "logs")
- os.makedirs(log_dir, exist_ok=True)
- __all__ = [
- "project_root",
- "config_dir",
- "spiders_config_path",
- "log_dir",
- "get_project_path"
- ]
- def get_project_path() -> str:
- """
- 获取 AutoScraperX 项目根路径
- 支持从任何子模块中调用而不会路径错乱
- """
- return project_root
|