File size: 849 Bytes
2628a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
import io
import traceback


def python_repl(code: str) -> str:
    """Execute Python code for calculations or data processing."""
    stdout_capture = io.StringIO()
    stderr_capture = io.StringIO()
    local_vars = {}
    try:
        sys.stdout = stdout_capture
        sys.stderr = stderr_capture
        exec(compile(code, "<string>", "exec"), {"__builtins__": __builtins__}, local_vars)
    except Exception:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        return f"Error:\n{traceback.format_exc()}"
    finally:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
    output = stdout_capture.getvalue()
    err = stderr_capture.getvalue()
    if err:
        return f"Stderr:\n{err}\nStdout:\n{output}"
    return output if output else "Code executed successfully (no output)."