python 运行时长限制装饰器
python 2.x 版
# -*- coding: utf-8 -*- import time from threading import Thread """ 运行时长设置 """ ThreadStop = Thread._Thread__stop def time_limited(timeout): def decorator(function): def decorator2(*args, **kwargs): class TimeLimited(Thread): def __init__(self, _error=None, ): Thread.__init__(self) self.error = _error self.result = None def run(self): try: self.result = function(*args, **kwargs) except Exception as e: self.error = e def stop(self): if self.isAlive(): ThreadStop(self) t = TimeLimited() t.start() t.join(timeout) if t.error: t.stop() raise t.error elif t.isAlive(): t.stop() raise ValueError('time out') return t.result return decorator2 return decorator if __name__ == "__main__": @time_limited(2) # 设置运行超时时间2S def fn_1(secs): time.sleep(secs) return 'Finished without timeout' try: print(fn_1(3)) # 设置函数执行3S except TestItemError as e: print(str(e))
python 3.x 版
# -*- coding: utf-8 -*- import time from threading import Thread def time_limited(timeout): def decorator(function): def decorator2(*args, **kwargs): class TimeLimited(Thread): def __init__(self, _error=None, ): Thread.__init__(self) self.error = _error self.result = None def run(self): try: self.result = function(*args, **kwargs) except Exception as e: self.error = e t = TimeLimited() t.setDaemon(True) t.start() t.join(timeout) if t.error: raise t.error elif t.is_alive(): raise TestItemError('time out') return t.result return decorator2 return decorator if __name__ == "__main__": @time_limited(2) # 设置运行超时时间2S def fn_1(secs): time.sleep(secs) return 'Finished without timeout' try: print(fn_1(3)) # 设置函数执行3S except TestItemError as e: print(str(e))