File size: 795 Bytes
293ab16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import contextlib
import traceback

def run_python_code(code: str, timeout_seconds: int = 5) -> dict:
    """
    Safely execute Python code and capture stdout and locals.
    Returns dict with either 'result' or 'error'.
    """
    local_vars = {}
    stdout = io.StringIO()
    try:
        with contextlib.redirect_stdout(stdout):
            # Optionally, you could run code with timeout or in sandbox here
            exec(code, {}, local_vars)
        return {
            "result": stdout.getvalue(),
            "locals": {k: repr(v) for k, v in local_vars.items()}
        }
    except Exception:
        err = traceback.format_exc()
        return {"error": err}

# Alias for convenience
safe_exec = run_python_code
execute_code = run_python_code
run_code = run_python_code