I’m calling a function in Python which I know may stall and force me to restart the script.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
Advertisement
Answer
You may use the signal package if you are running on UNIX:
JavaScript
x
46
46
1
In [1]: import signal
2
3
# Register an handler for the timeout
4
In [2]: def handler(signum, frame):
5
print("Forever is over!") :
6
raise Exception("end of time") :
7
:
8
9
# This function *may* run for an indetermined time...
10
In [3]: def loop_forever():
11
import time :
12
while 1: :
13
print("sec") :
14
time.sleep(1) :
15
:
16
:
17
18
# Register the signal function handler
19
In [4]: signal.signal(signal.SIGALRM, handler)
20
Out[4]: 0
21
22
# Define a timeout for your function
23
In [5]: signal.alarm(10)
24
Out[5]: 0
25
26
In [6]: try:
27
loop_forever() :
28
except Exception, exc: :
29
print(exc) :
30
.:
31
sec
32
sec
33
sec
34
sec
35
sec
36
sec
37
sec
38
sec
39
Forever is over!
40
end of time
41
42
# Cancel the timer if the function returned before timeout
43
# (ok, mine won't but yours maybe will :)
44
In [7]: signal.alarm(0)
45
Out[7]: 0
46
10 seconds after the call signal.alarm(10)
, the handler is called. This raises an exception that you can intercept from the regular Python code.
This module doesn’t play well with threads (but then, who does?)
Note that since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function:
JavaScript
1
8
1
def loop_forever():
2
while 1:
3
print('sec')
4
try:
5
time.sleep(10)
6
except:
7
continue
8