blob: 2b86bfb2ee2478be427fc37330b2edf804ae10eb (
plain)
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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2012-2013 by PN.
:license: MIT, see LICENSE for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import signal
############################################################
# Timeout
############################################################
#http://www.saltycrane.com/blog/2010/04/using-python-timeout-decorator-uploading-s3/
class TimeoutError(Exception):
def __init__(self, value="Timed Out"):
self.value = value
def __str__(self):
return repr(self.value)
def timeout(seconds=None):
def decorate(f):
def handler(signum, frame):
raise TimeoutError()
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
new_seconds = kwargs['timeout'] if 'timeout' in kwargs else seconds
if new_seconds is None:
raise ValueError("You must provide a timeout value")
signal.alarm(new_seconds)
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
|