File size: 1,042 Bytes
581f2e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import subprocess
import os
import tempfile

class Executor:
    def execute_code(self, code):
        try:
            # Save code to temporary file
            with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode="w") as temp_file:
                temp_file.write(code)
                temp_file_path = temp_file.name
            
            # Execute the code
            result = subprocess.run(
                ["python", temp_file_path],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            # Clean up
            os.unlink(temp_file_path)
            
            if result.returncode == 0:
                return result.stdout.strip() or "Code executed successfully"
            else:
                return f"Error: {result.stderr.strip() or 'Unknown error'}"
        
        except subprocess.TimeoutExpired:
            return "Error: Code execution timed out"
        except Exception as e:
            return f"Execution error: {str(e)}"