import sys from pathlib import Path def get_project_root(): """ 获取项目根路径(strategy_manager 的父目录) 项目结构: project/ ├── futures_trading_strategies/ └── strategy_manager/ """ # strategy_manager/core/path_utils.py -> strategy_manager -> project return Path(__file__).parent.parent.parent def get_strategy_root(config_path: str = "config/main.json"): """ 动态获取策略代码根路径 优先级: 1. config/main.json 中配置的绝对路径 2. config/main.json 中配置的相对路径(相对于项目根) 3. AUTO_DETECT: 自动探测项目根目录下的 futures_trading_strategies """ config_file = Path(config_path) strategy_root = None # 读取配置 if config_file.exists(): import json try: with open(config_file, 'r') as f: config = json.load(f) strategy_root = config.get("strategy_root", "AUTO_DETECT") except: strategy_root = "AUTO_DETECT" else: strategy_root = "AUTO_DETECT" # 如果是绝对路径,直接返回 if strategy_root and Path(strategy_root).is_absolute(): return Path(strategy_root) # 如果是相对路径,相对于项目根 project_root = get_project_root() if strategy_root and strategy_root != "AUTO_DETECT": return project_root / strategy_root # AUTO_DETECT模式: 探测项目根目录下的 futures_trading_strategies auto_detect = project_root / "futures_trading_strategies" if auto_detect.exists(): return auto_detect # 如果失败,抛出错误 raise RuntimeError( "无法自动探测策略代码路径,请在 config/main.json 中配置:\n" '"strategy_root": "/path/to/your/futures_trading_strategies"' ) def add_project_root_to_path(): """将项目根路径添加到 sys.path""" project_root = get_project_root() if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) print(f"[INFO] 已添加项目根路径到sys.path: {project_root}") return project_root def add_strategy_root_to_path(): """将策略根路径添加到 sys.path""" strategy_root = get_strategy_root() if str(strategy_root) not in sys.path: sys.path.insert(0, str(strategy_root)) print(f"[INFO] 已添加策略根路径到sys.path: {strategy_root}") return strategy_root