Python装饰器限制函数运行时间超时则退出执行 函数超时停止
2021/5/25 12:54:35
本文主要是介绍Python装饰器限制函数运行时间超时则退出执行 函数超时停止,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
https://www.jb51.net/article/159375.htm
# -*- coding: utf-8 -*- from threading import Thread import time class TimeoutException(Exception): pass ThreadStop = Thread._Thread__stop def timelimited(timeout): def decorator(function): def decorator2(*args,**kwargs): class TimeLimited(Thread): def __init__(self,_error= None,): Thread.__init__(self) self._error = _error def run(self): try: self.result = function(*args,**kwargs) except Exception,e: self._error = str(e) def _stop(self): if self.isAlive(): ThreadStop(self) t = TimeLimited() t.start() t.join(timeout) if isinstance(t._error,TimeoutException): t._stop() raise TimeoutException('timeout for %s' % (repr(function))) if t.isAlive(): t._stop() raise TimeoutException('timeout for %s' % (repr(function))) if t._error is None: return t.result return decorator2 return decorator @timelimited(2) # 设置运行超时时间2S def fn_1(secs): time.sleep(secs) return 'Finished without timeout' def do_something_after_timeout(): print('Time out!') if __name__ == "__main__": try: print(fn_1(3)) # 设置函数执行3S except TimeoutException as e: print(str(e)) do_something_after_timeout()
这篇关于Python装饰器限制函数运行时间超时则退出执行 函数超时停止的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础