36 lines
960 B
Python
Raw Normal View History

2025-11-04 08:09:12 +01:00
import contextlib
import os
2025-11-04 05:17:27 +01:00
import traceback
from io import StringIO
2025-11-04 08:09:12 +01:00
2025-11-04 05:17:27 +01:00
def python_exec(code, python_globals, cwd=None):
"""Execute Python code and capture the output.
Args:
code: The Python code to execute.
python_globals: Dictionary of global variables for execution.
cwd: Working directory for execution.
Returns:
Dict with status and output, or error information.
"""
2025-11-04 05:17:27 +01:00
try:
original_cwd = None
if cwd:
original_cwd = os.getcwd()
os.chdir(cwd)
2025-11-04 05:17:27 +01:00
output = StringIO()
with contextlib.redirect_stdout(output):
exec(code, python_globals)
if original_cwd:
os.chdir(original_cwd)
2025-11-04 05:17:27 +01:00
return {"status": "success", "output": output.getvalue()}
except Exception as e:
if original_cwd:
os.chdir(original_cwd)
2025-11-04 05:17:27 +01:00
return {"status": "error", "error": str(e), "traceback": traceback.format_exc()}