Spaces:
Sleeping
Sleeping
Added multi language support
Browse files
utils.py
CHANGED
|
@@ -1,12 +1,15 @@
|
|
| 1 |
import sys
|
|
|
|
|
|
|
| 2 |
from io import StringIO
|
| 3 |
import contextlib
|
| 4 |
-
import
|
| 5 |
from datetime import datetime
|
|
|
|
| 6 |
|
| 7 |
@contextlib.contextmanager
|
| 8 |
def capture_output():
|
| 9 |
-
"""Capture stdout and stderr"""
|
| 10 |
stdout, stderr = StringIO(), StringIO()
|
| 11 |
old_out, old_err = sys.stdout, sys.stderr
|
| 12 |
try:
|
|
@@ -15,32 +18,130 @@ def capture_output():
|
|
| 15 |
finally:
|
| 16 |
sys.stdout, sys.stderr = old_out, old_err
|
| 17 |
|
| 18 |
-
def execute_code(code: str, stdin: str = "") ->
|
| 19 |
"""
|
| 20 |
-
Execute the
|
|
|
|
|
|
|
| 21 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
with capture_output() as (stdout, stderr):
|
| 23 |
try:
|
| 24 |
-
# Create a generator for stdin lines
|
| 25 |
inputs = iter(stdin.splitlines())
|
| 26 |
-
|
| 27 |
-
# Proper lambda that accepts optional prompt
|
| 28 |
input_override = lambda prompt='': next(inputs, '')
|
| 29 |
-
|
| 30 |
local_vars = {"input": input_override}
|
| 31 |
exec(code, {}, local_vars)
|
| 32 |
-
|
| 33 |
return stdout.getvalue().strip(), stderr.getvalue().strip(), None
|
| 34 |
except Exception as e:
|
| 35 |
return stdout.getvalue().strip(), stderr.getvalue().strip(), str(e)
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def export_session(code: str, output: str, error: str) -> dict:
|
| 38 |
-
"""
|
| 39 |
-
Create an exportable session object
|
| 40 |
-
"""
|
| 41 |
return {
|
| 42 |
"timestamp": datetime.now().isoformat(),
|
| 43 |
"code": code,
|
| 44 |
"output": output,
|
| 45 |
"error": error
|
| 46 |
-
}
|
|
|
|
| 1 |
import sys
|
| 2 |
+
import os
|
| 3 |
+
import subprocess
|
| 4 |
from io import StringIO
|
| 5 |
import contextlib
|
| 6 |
+
import tempfile
|
| 7 |
from datetime import datetime
|
| 8 |
+
from typing import Tuple
|
| 9 |
|
| 10 |
@contextlib.contextmanager
|
| 11 |
def capture_output():
|
| 12 |
+
"""Capture stdout and stderr for Python code"""
|
| 13 |
stdout, stderr = StringIO(), StringIO()
|
| 14 |
old_out, old_err = sys.stdout, sys.stderr
|
| 15 |
try:
|
|
|
|
| 18 |
finally:
|
| 19 |
sys.stdout, sys.stderr = old_out, old_err
|
| 20 |
|
| 21 |
+
def execute_code(code: str, stdin: str = "", language: str = "python") -> Tuple[str, str, str]:
|
| 22 |
"""
|
| 23 |
+
Execute code in the specified language and return (stdout, stderr, exception)
|
| 24 |
+
|
| 25 |
+
Currently supports: python (default). Other languages scaffolded.
|
| 26 |
"""
|
| 27 |
+
try:
|
| 28 |
+
if language == "python":
|
| 29 |
+
return _execute_python(code, stdin)
|
| 30 |
+
|
| 31 |
+
elif language == "c":
|
| 32 |
+
return _execute_c(code, stdin)
|
| 33 |
+
|
| 34 |
+
elif language == "cpp":
|
| 35 |
+
return _execute_cpp(code, stdin)
|
| 36 |
+
|
| 37 |
+
elif language == "java":
|
| 38 |
+
return _execute_java(code, stdin)
|
| 39 |
+
|
| 40 |
+
elif language == "js":
|
| 41 |
+
return _execute_javascript(code, stdin)
|
| 42 |
+
|
| 43 |
+
elif language == "csharp":
|
| 44 |
+
return _execute_csharp(code, stdin)
|
| 45 |
+
|
| 46 |
+
else:
|
| 47 |
+
return "", f"Unsupported language: {language}", None
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return "", "", str(e)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _execute_python(code: str, stdin: str) -> Tuple[str, str, str]:
|
| 54 |
with capture_output() as (stdout, stderr):
|
| 55 |
try:
|
|
|
|
| 56 |
inputs = iter(stdin.splitlines())
|
|
|
|
|
|
|
| 57 |
input_override = lambda prompt='': next(inputs, '')
|
|
|
|
| 58 |
local_vars = {"input": input_override}
|
| 59 |
exec(code, {}, local_vars)
|
|
|
|
| 60 |
return stdout.getvalue().strip(), stderr.getvalue().strip(), None
|
| 61 |
except Exception as e:
|
| 62 |
return stdout.getvalue().strip(), stderr.getvalue().strip(), str(e)
|
| 63 |
|
| 64 |
+
|
| 65 |
+
def _run_subprocess(cmd, stdin_input=None) -> Tuple[str, str, str]:
|
| 66 |
+
try:
|
| 67 |
+
result = subprocess.run(
|
| 68 |
+
cmd,
|
| 69 |
+
input=stdin_input.encode() if stdin_input else None,
|
| 70 |
+
stdout=subprocess.PIPE,
|
| 71 |
+
stderr=subprocess.PIPE,
|
| 72 |
+
timeout=10
|
| 73 |
+
)
|
| 74 |
+
return result.stdout.decode(), result.stderr.decode(), None
|
| 75 |
+
except Exception as e:
|
| 76 |
+
return "", "", str(e)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _execute_c(code: str, stdin: str):
|
| 80 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 81 |
+
source_path = os.path.join(tmp, "main.c")
|
| 82 |
+
binary_path = os.path.join(tmp, "main.out")
|
| 83 |
+
with open(source_path, "w") as f:
|
| 84 |
+
f.write(code)
|
| 85 |
+
compile_cmd = ["gcc", source_path, "-o", binary_path]
|
| 86 |
+
compile_out, compile_err, exc = _run_subprocess(compile_cmd)
|
| 87 |
+
if exc or compile_err:
|
| 88 |
+
return compile_out, compile_err, exc
|
| 89 |
+
return _run_subprocess([binary_path], stdin)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _execute_cpp(code: str, stdin: str):
|
| 93 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 94 |
+
source_path = os.path.join(tmp, "main.cpp")
|
| 95 |
+
binary_path = os.path.join(tmp, "main.out")
|
| 96 |
+
with open(source_path, "w") as f:
|
| 97 |
+
f.write(code)
|
| 98 |
+
compile_cmd = ["g++", source_path, "-o", binary_path]
|
| 99 |
+
compile_out, compile_err, exc = _run_subprocess(compile_cmd)
|
| 100 |
+
if exc or compile_err:
|
| 101 |
+
return compile_out, compile_err, exc
|
| 102 |
+
return _run_subprocess([binary_path], stdin)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _execute_java(code: str, stdin: str):
|
| 106 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 107 |
+
class_name = "Main"
|
| 108 |
+
source_path = os.path.join(tmp, f"{class_name}.java")
|
| 109 |
+
with open(source_path, "w") as f:
|
| 110 |
+
f.write(code)
|
| 111 |
+
compile_cmd = ["javac", source_path]
|
| 112 |
+
compile_out, compile_err, exc = _run_subprocess(compile_cmd)
|
| 113 |
+
if exc or compile_err:
|
| 114 |
+
return compile_out, compile_err, exc
|
| 115 |
+
return _run_subprocess(["java", "-cp", tmp, class_name], stdin)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _execute_javascript(code: str, stdin: str):
|
| 119 |
+
with tempfile.NamedTemporaryFile(suffix=".js", delete=False, mode="w") as f:
|
| 120 |
+
f.write(code)
|
| 121 |
+
temp_path = f.name
|
| 122 |
+
try:
|
| 123 |
+
return _run_subprocess(["node", temp_path], stdin)
|
| 124 |
+
finally:
|
| 125 |
+
os.remove(temp_path)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _execute_csharp(code: str, stdin: str):
|
| 129 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 130 |
+
source_path = os.path.join(tmp, "main.cs")
|
| 131 |
+
binary_path = os.path.join(tmp, "main.exe")
|
| 132 |
+
with open(source_path, "w") as f:
|
| 133 |
+
f.write(code)
|
| 134 |
+
compile_cmd = ["mcs", source_path, "-out:" + binary_path]
|
| 135 |
+
compile_out, compile_err, exc = _run_subprocess(compile_cmd)
|
| 136 |
+
if exc or compile_err:
|
| 137 |
+
return compile_out, compile_err, exc
|
| 138 |
+
return _run_subprocess(["mono", binary_path], stdin)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
def export_session(code: str, output: str, error: str) -> dict:
|
|
|
|
|
|
|
|
|
|
| 142 |
return {
|
| 143 |
"timestamp": datetime.now().isoformat(),
|
| 144 |
"code": code,
|
| 145 |
"output": output,
|
| 146 |
"error": error
|
| 147 |
+
}
|