函数的超时
1、使用信号量实现函数的超时功能
from functools import wraps import errno import os import signal import time class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator
超时异常的修改:
class TimeoutError(Exception): def __init__(self, message=None, **kwargs): self.message = message super(TimeoutError, self).__init__(**kwargs) def __str__(self): return self.message
2、使用eventlet的Timeout
3、使用线程的Timer
http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish