""" 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