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