261.2.2
by jtv at canonical
Format imports. |
1 |
import errno |
146
by Diogo Matsubara
add timeout decorator |
2 |
from functools import wraps |
3 |
import os |
|
4 |
import signal |
|
5 |
||
261.2.1
by jtv at canonical
Add lint test, and fix lint. |
6 |
|
146
by Diogo Matsubara
add timeout decorator |
7 |
class TimeoutError(Exception): |
8 |
pass
|
|
9 |
||
261.2.1
by jtv at canonical
Add lint test, and fix lint. |
10 |
|
265.2.2
by Jeroen Vermeulen
Typo in original. |
11 |
# From StackOverflow question: "timeout function if it takes too long to
|
265.2.1
by Jeroen Vermeulen
De-duplicate definition of the timeout decorator. |
12 |
# finish": http://bit.ly/1g1wHpm
|
146
by Diogo Matsubara
add timeout decorator |
13 |
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): |
14 |
def decorator(func): |
|
15 |
def _handle_timeout(signum, frame): |
|
16 |
raise TimeoutError(error_message) |
|
17 |
||
18 |
def wrapper(*args, **kwargs): |
|
19 |
signal.signal(signal.SIGALRM, _handle_timeout) |
|
20 |
signal.alarm(seconds) |
|
21 |
try: |
|
22 |
result = func(*args, **kwargs) |
|
23 |
finally: |
|
24 |
signal.alarm(0) |
|
25 |
return result |
|
26 |
||
27 |
return wraps(func)(wrapper) |
|
28 |
||
29 |
return decorator |