Spaces:
Sleeping
Sleeping
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 | |