Spaces:
Runtime error
Runtime error
Upload code_executor.py
Browse files- code_executor.py +25 -0
code_executor.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import io
|
| 3 |
+
import sys
|
| 4 |
+
import contextlib
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
class CodeExecutor:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
def run_code(self, code: str):
|
| 12 |
+
stdout = io.StringIO()
|
| 13 |
+
stderr = io.StringIO()
|
| 14 |
+
local_vars = {}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
| 18 |
+
exec(code, {}, local_vars)
|
| 19 |
+
return {"output": stdout.getvalue(), "error": stderr.getvalue()}
|
| 20 |
+
except Exception:
|
| 21 |
+
return {"output": stdout.getvalue(), "error": traceback.format_exc()}
|
| 22 |
+
|
| 23 |
+
def test_function(self, code: str, test_code: str):
|
| 24 |
+
combined = code + "\n" + test_code
|
| 25 |
+
return self.run_code(combined)
|