forked from martius-lab/EQL_Tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeout.py
34 lines (28 loc) · 846 Bytes
/
timeout.py
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
32
33
34
import signal
import threading
from contextlib import contextmanager
from six.moves import _thread
class TimeoutException(Exception):
pass
@contextmanager
def time_limit(seconds):
if hasattr(signal, "SIGALRM"):
# for Linux
def signal_handler(signum, frame):
raise TimeoutException("Timeout after {} seconds.".format(seconds))
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
else:
# for Windows
timer = threading.Timer(seconds, lambda: _thread.interrupt_main())
timer.start()
try:
yield
except KeyboardInterrupt:
raise TimeoutException("Timeout after {} seconds.".format(seconds))
finally:
timer.cancel()