-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeout.py
More file actions
40 lines (31 loc) · 913 Bytes
/
Timeout.py
File metadata and controls
40 lines (31 loc) · 913 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
32
33
34
35
36
37
38
39
40
class TimeoutLinux:
"""
Usage:
with Timeout(seconds=3):
do_things
"""
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
class TimeoutMac:
"""
Does nothing. This class is not possible on a Mac.
"""
def __init__(self, seconds=1, error_message='Timeout'):
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
if platform.system() == 'Linux':
signal = __import__('signal')
Timeout = TimeoutLinux
else:
Timeout = TimeoutMac