-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcode.py
More file actions
31 lines (26 loc) · 1019 Bytes
/
Copy pathcode.py
File metadata and controls
31 lines (26 loc) · 1019 Bytes
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
import multiprocessing
from typing import Optional
# Docs
# [queue](https://docs.python.org/3/library/multiprocessing.html#pipes-and-queues)
class PythonREPL:
@classmethod
def worker(cls, code: str, globals, locals, queue):
try:
exec(code, globals, locals)
queue.put(None)
except Exception as e:
queue.put(repr(e))
def run(self, command: str, timeout=5, globals={}, locals=None) -> Optional[str]:
queue: multiprocessing.Queue = multiprocessing.Queue()
p = multiprocessing.Process(
target=self.worker, args=(command, globals, locals, queue),
)
p.start()
p.join(timeout)
if p.is_alive():
p.terminate()
return "TimeoutError"
return queue.get_nowait()
# We had to move the code above to a class for pickle reasons
def execute_code(command: str, timeout=5, globals={}, locals=None) -> Optional[str]:
return PythonREPL().run(command, timeout, globals, locals)