File size: 1,426 Bytes
51f6ad6
 
83c608b
51f6ad6
83c608b
 
 
 
 
 
bb34272
83c608b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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