File size: 2,296 Bytes
86a8165 | 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | """
Sandbox execution module.
Runs user-generated Python code in an isolated subprocess with timeout.
"""
import os
import sys
import subprocess
import tempfile
from pathlib import Path
ALLOWED_IMPORTS = {
"pandas", "numpy", "scipy", "matplotlib", "seaborn",
"sklearn", "statsmodels", "openpyxl", "json", "os",
"warnings", "math", "re", "collections", "itertools",
"functools", "datetime", "io", "base64",
}
def execute_code(
code: str,
data_path: str,
output_dir: str,
result_file: str,
timeout: int = 120,
) -> dict:
"""
Execute Python analysis code in a subprocess.
Injects context variables (DATA_PATH, OUTPUT_DIR, RESULT_FILE) before
the user code, then runs it in the current Python interpreter.
Returns:
dict with keys: success (bool), stdout (str), stderr (str), returncode (int)
"""
setup_code = f"""
import os
import warnings
warnings.filterwarnings('ignore')
DATA_PATH = {repr(data_path)}
OUTPUT_DIR = {repr(output_dir)}
RESULT_FILE = {repr(result_file)}
os.makedirs(OUTPUT_DIR, exist_ok=True)
"""
full_code = setup_code + "\n" + code
# Write to a temporary file
tmp = tempfile.NamedTemporaryFile(
mode="w", suffix=".py", delete=False, encoding="utf-8"
)
try:
tmp.write(full_code)
tmp.flush()
tmp.close()
result = subprocess.run(
[sys.executable, tmp.name],
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
return {
"success": result.returncode == 0,
"stdout": result.stdout[:4000],
"stderr": result.stderr[:4000],
"returncode": result.returncode,
}
except subprocess.TimeoutExpired:
return {
"success": False,
"stdout": "",
"stderr": "TimeoutExpired: 분석이 120초를 초과했습니다.",
"returncode": -1,
}
except Exception as exc:
return {
"success": False,
"stdout": "",
"stderr": str(exc),
"returncode": -1,
}
finally:
try:
os.unlink(tmp.name)
except OSError:
pass
|