from pathlib import Path import subprocess import sys PROJECT_ROOT = Path(__file__).resolve().parents[4] def run_publisher(topic_id: str = None): """运行发布包生成脚本 Args: topic_id: 可选,指定单个选题ID Returns: dict: 包含 ok, result/error, topic_id 等字段 """ try: script_path = PROJECT_ROOT / "scripts" / "publisher.py" if not script_path.exists(): return {"ok": False, "error": f"Publisher script not found: {script_path}"} cmd = [sys.executable, str(script_path)] if topic_id: cmd.extend(["--topic-id", topic_id]) result = subprocess.run( cmd, capture_output=True, text=True, cwd=PROJECT_ROOT, timeout=300 # 5分钟超时 ) if result.returncode == 0: return { "ok": True, "result": result.stdout, "topic_id": topic_id } else: return { "ok": False, "error": result.stderr, "result": result.stdout, "topic_id": topic_id } except subprocess.TimeoutExpired: return {"ok": False, "error": "Publisher timed out after 5 minutes", "topic_id": topic_id} except Exception as e: return {"ok": False, "error": str(e), "topic_id": topic_id}