我也不得不这样做。我创建了一个模块,它提供了一个修饰符来限制函数的运行时:import logging
import signal
from functools import wraps
MODULELOG = logging.getLogger(__name__)
class Timeout(Exception):
"""The timeout handler was invoked"""
def _timeouthandler(signum, frame):
"""This function is called by SIGALRM"""
MODULELOG.info('Invoking the timeout')
raise Timeout
def timeout(seconds):
"""Decorate a function to set a timeout on its execution"""
def wrap(func):
"""Wrap a timer around the given function"""
@wraps(func)
def inner(*args, **kwargs):
"""Set an execution timer, execute the wrapped function,
then clear the timer."""
MODULELOG.debug('setting an alarm for %d seconds on %s' % (seconds, func))
oldsignal = signal.signal(signal.SIGALRM, _timeouthandler)
signal.alarm(seconds)
try:
return func(*args, **kwargs)
finally:
MODULELOG.debug('clearing the timer on %s' % func)
signal.alarm(0)
signal.signal(signal.SIGALRM, oldsignal)
return inner
return wrap
我用它就像:
^{pr2}$
在我的例子中,dosomething正在调用一个外部程序,它会周期性地挂起,我希望能够在发生这种情况时干净地退出。在