-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeout.py
74 lines (66 loc) · 1.76 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/local/cdat/bin/python
# timeout by function decoration. based on recipe in
# http://code.activestate.com/recipes/307871-timing-out-function/
import signal, time
class TimedOutExc(Exception):
def __init__(self, value = "Timed Out"):
self.value = value
def __str__(self):
return repr(self.value)
def timed_out(timeout):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
result = f(*args, **kwargs)
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
new_f.func_name = f.func_name
return new_f
return decorate
# # test examples:
#
# def fn_1(secs):
# time.sleep(secs)
# return "Finished"
# @timed_out(4)
# def fn_2(secs):
# time.sleep(secs)
# return("Finished")
# @timed_out(2)
# def fn_3(secs):
# time.sleep(secs)
# return "Finished"
# @timed_out(2)
# def fn_4(secs):
# try:
# time.sleep(secs)
# return "Finished"
# except TimedOutExc:
# print "(Caught TimedOutExc, so cleaining up, and re-raising it) - ",
# raise TimedOutExc
#
# if __name__ == '__main__':
#
# try:
# print "fn_2 (sleep 2, timeout 4): ",
# print fn_2(2)
# except TimedOutExc:
# print "took too long"
#
# try:
# print "fn_3 (sleep 4, timeout 2): ",
# print fn_3(4)
# except TimedOutExc:
# print "took too long"
#
# try:
# print "fn_4 (sleep 4, timeout 2): ",
# print fn_4(4)
# except TimedOutExc:
# print "took too long"