"""Python 运行工具:直接执行一段 Python 代码或一个 .py 文件,拿回输出。 - 子进程运行,崩溃不影响内核 - 需要联网时可以直接 import requests / httpx / urllib(装了就有) - `libs` 动作可以列出当前环境装了哪些常用库 """ import importlib.util import os import subprocess import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _protocol import serve # noqa: E402 TOOL = { "name": "python_run", "description": ( "运行一段 Python 代码或指定 .py 文件,返回标准输出/错误。" "适合做计算、数据处理、调用网络接口(requests/httpx/urllib 可用)。" "action=libs 可以查看当前环境装了哪些库。" ), "parameters": { "type": "object", "properties": { "action": { "type": "string", "enum": ["run", "libs"], "description": "run=执行代码/文件(默认);libs=列出可用库", }, "code": {"type": "string", "description": "要执行的 Python 代码(action=run 时二选一)"}, "file": {"type": "string", "description": "要执行的 .py 文件路径(action=run 时二选一)"}, "stdin": {"type": "string", "description": "传给脚本的标准输入,可留空"}, "timeout": {"type": "number", "description": "超时秒数,默认 60,最大 600"}, }, }, } WATCHED = [ "requests", "httpx", "aiohttp", "urllib3", "bs4", "lxml", "pandas", "numpy", "PIL", "openpyxl", "docx", "pptx", "yaml", "dotenv", "mcp", "flask", "fastapi", ] def python_bin(): """优先用当前解释器;安卓上没有独立解释器时返回 None(由内核在进程内执行)""" if sys.executable and os.path.basename(sys.executable).lower().startswith("python"): return sys.executable for name in ("python3", "python"): for folder in os.environ.get("PATH", "").split(os.pathsep): candidate = os.path.join(folder, name) if os.path.isfile(candidate): return candidate return sys.executable or "python" def run(args): action = str(args.get("action") or "run").lower() if action == "libs": available = [] missing = [] for name in WATCHED: (available if importlib.util.find_spec(name) else missing).append(name) return { "python": sys.version.split()[0], "executable": sys.executable, "available": available, "missing": missing, "hint": "缺库时可以用 shell 工具执行 pip install <包名>" if missing else "常用库齐全", } code = args.get("code") file_path = args.get("file") if not code and not file_path: raise ValueError("code 和 file 至少要给一个") timeout = max(1, min(600, int(args.get("timeout", 60) or 60))) stdin_text = args.get("stdin") or "" cleanup = None if file_path: target = str(file_path) if not os.path.isfile(target): raise ValueError(f"文件不存在:{target}") else: fd, target = tempfile.mkstemp(suffix=".py", prefix="doubao_run_") with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(str(code)) cleanup = target try: proc = subprocess.run( [python_bin(), target], input=stdin_text, capture_output=True, timeout=timeout, text=True, errors="replace", cwd=os.path.dirname(os.path.abspath(target)), ) return { "exit_code": proc.returncode, "stdout": (proc.stdout or "")[-12000:], "stderr": (proc.stderr or "")[-6000:], } except subprocess.TimeoutExpired: return {"error": f"执行超时({timeout}s)", "timeout": True} finally: if cleanup: try: os.unlink(cleanup) except OSError: pass if __name__ == "__main__": serve(TOOL, run)