jatinror commited on
Commit
7b4a61e
·
verified ·
1 Parent(s): 4eb6c82

Create python_runner.py

Browse files
Files changed (1) hide show
  1. tools/python_runner.py +52 -0
tools/python_runner.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+ import io
3
+ import traceback
4
+ import contextlib
5
+ import signal
6
+
7
+ class TimeoutException(Exception):
8
+ pass
9
+
10
+ def timeout_handler(signum, frame):
11
+ raise TimeoutException("Execution timed out.")
12
+
13
+ def run_python(code: str, timeout: int = 5) -> Dict[str, Any]:
14
+ """
15
+ Safely execute Python code and capture output/errors.
16
+ """
17
+
18
+ safe_globals = {
19
+ "__builtins__": {
20
+ "print": print,
21
+ "range": range,
22
+ "len": len,
23
+ "int": int,
24
+ "float": float,
25
+ "str": str,
26
+ "list": list,
27
+ "dict": dict,
28
+ "sum": sum,
29
+ "min": min,
30
+ "max": max,
31
+ "abs": abs,
32
+ }
33
+ }
34
+
35
+ stdout_buffer = io.StringIO()
36
+
37
+ try:
38
+ signal.signal(signal.SIGALRM, timeout_handler)
39
+ signal.alarm(timeout)
40
+
41
+ with contextlib.redirect_stdout(stdout_buffer):
42
+ exec(code, safe_globals, {})
43
+
44
+ signal.alarm(0)
45
+
46
+ return {"status": "success", "output": stdout_buffer.getvalue()}
47
+
48
+ except TimeoutException as e:
49
+ return {"status": "error", "output": str(e)}
50
+
51
+ except Exception:
52
+ return {"status": "error", "output": traceback.format_exc()}