File size: 1,223 Bytes
906d397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import subprocess
import sys
import os
import tempfile
import shutil

def execute_python_code(code: str, timeout: int = 30) -> dict:
    """
    Executes Python code in a temporary directory and returns the output.
    """
    temp_dir = tempfile.mkdtemp()
    script_path = os.path.join(temp_dir, "script.py")

    with open(script_path, "w") as f:
        f.write(code)
    
    python_executable = sys.executable
    
    try:
        print(f"🧪 Executing code in a temporary environment...")
        process = subprocess.run(
            [python_executable, script_path],
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=temp_dir
        )
        
        stdout = process.stdout
        stderr = process.stderr
        success = process.returncode == 0
        
    except subprocess.TimeoutExpired:
        stdout = ""
        stderr = f"Execution timed out after {timeout} seconds."
        success = False
    except Exception as e:
        stdout = ""
        stderr = f"An unexpected error occurred: {str(e)}"
        success = False
    finally:
        shutil.rmtree(temp_dir)
        
    return {"stdout": stdout, "stderr": stderr, "success": success}