Spaces:
Runtime error
Runtime error
File size: 799 Bytes
cc15101 | 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 | import os
import subprocess
import tempfile
TIMEOUT = 5 # SECONDS
def run_code(code: str) -> str:
try:
with tempfile.NamedTemporaryFile(suffix=".py", mode="w", delete=False) as f:
f.write(code)
path = f.name
result = subprocess.run(
["python", path],
capture_output=True,
text=True,
timeout=TIMEOUT,
)
os.unlink(path)
stdout = result.stdout.strip()
stderr = result.stderr.strip()
if stderr:
return f"stdout: {stdout}\nstderr: {stderr}"
return stdout or "(no output)"
except subprocess.TimeoutExpired:
return f"Timed out after {TIMEOUT}s"
except Exception as e:
return f"Code runner error: {e}" |