File size: 8,580 Bytes
092e3d5 | 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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | import subprocess
import os
import tempfile
from typing import Dict, Optional
class CodeExecutor:
def __init__(self, timeout: int = 10):
self.timeout = timeout
def execute(self, code: str, language: str = "python", stdin_input: str = None) -> Dict:
"""Execute code in the specified language, optionally piping stdin_input."""
language = language.lower().strip()
if language in ["python", "py"]:
return self._execute_python(code, stdin_input)
elif language in ["javascript", "js"]:
return self._execute_javascript(code, stdin_input)
elif language == "java":
return self._execute_java(code, stdin_input)
elif language in ["cpp", "c++"]:
return self._execute_cpp(code, stdin_input)
else:
return {
"success": False,
"error": f"Unsupported language: {language}"
}
def execute_with_test_case(self, code: str, language: str, input_data: str, expected_output: str) -> Dict:
"""
Execute code with given stdin input and compare output with expected.
Returns result with pass/fail, actual output, etc.
"""
result = self.execute(code, language, stdin_input=input_data)
if not result.get("success"):
return {
"passed": False,
"actual_output": result.get("error", ""),
"expected_output": expected_output.strip(),
"error": result.get("error", "Execution failed"),
"status": "Runtime Error" if "timeout" not in result.get("error", "").lower() else "Time Limit Exceeded"
}
actual = result.get("output", "").strip()
expected = expected_output.strip()
passed = actual == expected
return {
"passed": passed,
"actual_output": actual,
"expected_output": expected,
"error": None,
"status": "Accepted" if passed else "Wrong Answer"
}
def _execute_python(self, code: str, stdin_input: str = None) -> Dict:
"""Execute Python code"""
try:
result = subprocess.run(
["python", "-c", code],
capture_output=True,
text=True,
timeout=self.timeout,
input=stdin_input
)
if result.returncode == 0:
return {
"success": True,
"output": result.stdout if result.stdout else "(No output)"
}
else:
return {
"success": False,
"error": result.stderr if result.stderr else "Unknown error"
}
except subprocess.TimeoutExpired:
return {
"success": False,
"error": f"Code execution timeout (>{self.timeout}s)"
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def _execute_javascript(self, code: str, stdin_input: str = None) -> Dict:
"""Execute JavaScript code using Node.js"""
try:
result = subprocess.run(
["node", "-e", code],
capture_output=True,
text=True,
timeout=self.timeout,
input=stdin_input
)
if result.returncode == 0:
return {
"success": True,
"output": result.stdout if result.stdout else "(No output)"
}
else:
return {
"success": False,
"error": result.stderr if result.stderr else "Unknown error"
}
except subprocess.TimeoutExpired:
return {
"success": False,
"error": f"Code execution timeout (>{self.timeout}s)"
}
except FileNotFoundError:
return {
"success": False,
"error": "Node.js not installed. Install Node.js to run JavaScript"
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def _execute_java(self, code: str, stdin_input: str = None) -> Dict:
"""Execute Java code"""
try:
# Create temp directory
with tempfile.TemporaryDirectory() as tmpdir:
# Write Java file
java_file = os.path.join(tmpdir, "Main.java")
with open(java_file, "w") as f:
f.write(code)
# Compile
compile_result = subprocess.run(
["javac", java_file],
capture_output=True,
text=True,
timeout=self.timeout
)
if compile_result.returncode != 0:
return {
"success": False,
"error": compile_result.stderr if compile_result.stderr else "Compilation error"
}
# Run
run_result = subprocess.run(
["java", "-cp", tmpdir, "Main"],
capture_output=True,
text=True,
timeout=self.timeout,
input=stdin_input
)
if run_result.returncode == 0:
return {
"success": True,
"output": run_result.stdout if run_result.stdout else "(No output)"
}
else:
return {
"success": False,
"error": run_result.stderr if run_result.stderr else "Runtime error"
}
except subprocess.TimeoutExpired:
return {
"success": False,
"error": f"Code execution timeout (>{self.timeout}s)"
}
except FileNotFoundError:
return {
"success": False,
"error": "Java not installed. Install JDK to run Java code"
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def _execute_cpp(self, code: str, stdin_input: str = None) -> Dict:
"""Execute C++ code"""
try:
with tempfile.TemporaryDirectory() as tmpdir:
# Write C++ file
cpp_file = os.path.join(tmpdir, "main.cpp")
exe_file = os.path.join(tmpdir, "main")
with open(cpp_file, "w") as f:
f.write(code)
# Compile
compile_result = subprocess.run(
["g++", cpp_file, "-o", exe_file],
capture_output=True,
text=True,
timeout=self.timeout
)
if compile_result.returncode != 0:
return {
"success": False,
"error": compile_result.stderr if compile_result.stderr else "Compilation error"
}
# Run
run_result = subprocess.run(
[exe_file],
capture_output=True,
text=True,
timeout=self.timeout,
input=stdin_input
)
if run_result.returncode == 0:
return {
"success": True,
"output": run_result.stdout if run_result.stdout else "(No output)"
}
else:
return {
"success": False,
"error": run_result.stderr if run_result.stderr else "Runtime error"
}
except subprocess.TimeoutExpired:
return {
"success": False,
"error": f"Code execution timeout (>{self.timeout}s)"
}
except FileNotFoundError:
return {
"success": False,
"error": "G++ not installed. Install GCC to run C++ code"
}
except Exception as e:
return {
"success": False,
"error": str(e)
} |