import io import contextlib import threading def python_repl(code: str, timeout: int = 10) -> str: """Execute Python code and return its printed output. Use for calculations, string manipulation, parsing tables, etc. You MUST use `print()` to output results. Available libraries: pandas (as pd), numpy (as np).""" buffer = io.StringIO() # 预导入常用库 namespace = {} try: import pandas as pd import numpy as np namespace['pd'] = pd namespace['np'] = np except ImportError: pass # 如果未安装,仍可运行 result = {"output": "", "error": None} def run(): try: with contextlib.redirect_stdout(buffer): exec(code, namespace) result["output"] = buffer.getvalue() except Exception as e: result["error"] = str(e) thread = threading.Thread(target=run) thread.start() thread.join(timeout) if thread.is_alive(): return f"Error: Code execution timed out after {timeout} seconds. Please simplify or use print statements." if result["error"]: return f"Error: {result['error']}\nOutput before error:\n{buffer.getvalue()}" output = result["output"] if not output.strip(): return "Code ran successfully but printed nothing. Remember to print() your result." return output