2025-11-04 08:09:12 +01:00
|
|
|
import contextlib
|
2025-11-05 15:34:23 +01:00
|
|
|
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
|
|
|
|
2025-11-05 15:34:23 +01:00
|
|
|
def python_exec(code, python_globals, cwd=None):
|
2025-11-06 15:15:06 +01:00
|
|
|
"""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:
|
2025-11-05 15:34:23 +01:00
|
|
|
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)
|
|
|
|
|
|
2025-11-05 15:34:23 +01:00
|
|
|
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:
|
2025-11-05 15:34:23 +01:00
|
|
|
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()}
|