-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathtimeout.py
35 lines (30 loc) · 878 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
35
'''
Copyright 2015-2022 HENNGE K.K. (formerly known as HDE, Inc.)
Licensed under MIT.
'''
import signal
import threading
from contextlib import contextmanager
import _thread
class TimeoutException(Exception):
pass
@contextmanager
def time_limit(seconds):
if hasattr(signal, "SIGALRM"):
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:
timer = threading.Timer(seconds, lambda: _thread.interrupt_main())
timer.start()
try:
yield
except KeyboardInterrupt:
raise TimeoutException("Timeout after {} seconds.".format(seconds))
finally:
timer.cancel()