python使用装饰器和线程限制函数执行时间的方法
作者:lele 时间:2022-04-03 04:06:34
本文实例讲述了python使用装饰器和线程限制函数执行时间的方法。分享给大家供大家参考。具体分析如下:
很多时候函数内部包含了一些不可预知的事情,比如调用其它软件,从网络抓取信息,可能某个函数会卡在某个地方不动态,这段代码可以用来限制函数的执行时间,只需要在函数的上方添加一个装饰器,timelimited(2)就可以限定函数必须在2秒内执行完成,如果执行完成则返回函数正常的返回值,如果执行超时则会抛出错误信息。
# -*- 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 =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)
def fn_1(secs):
time.sleep(secs)
return 'Finished'
if __name__ == "__main__":
print fn_1(4)
希望本文所述对大家的Python程序设计有所帮助。
标签:python,函数,执行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
页面制作的重要性
2007-10-30 13:14:00
![](https://img.aspxhome.com/file/UploadPic/200710/30/2007103013184371s.gif)
Python对list列表结构中的值进行去重的方法总结
2021-10-18 04:09:04
JS动态添加与删除select中的Option对象(示例代码)
2023-09-17 02:15:31
python高阶函数functools模块的具体使用
2022-12-08 09:03:15
Python 文本文件与csv文件的读取与写入
2021-02-10 09:57:56
python自动化测试之如何解析excel文件
2022-08-28 08:24:36
Python入门教程之运算符与控制流
2022-08-04 03:38:40
![](https://img.aspxhome.com/file/2023/8/89008_0s.png)
python机器学习基础K近邻算法详解KNN
2024-01-01 05:44:57
![](https://img.aspxhome.com/file/2023/9/78739_0s.png)
ASP中 ADODB.Stream 语法速查
2008-01-27 15:23:00
XML与HTML的结合(上)
2008-09-05 17:19:00
如何基于Python爬取隐秘的角落评论
2022-02-17 05:31:43
![](https://img.aspxhome.com/file/2023/2/87902_0s.jpg)
Python爬虫使用Selenium+PhantomJS抓取Ajax和动态HTML内容
2023-04-01 15:20:05
![](https://img.aspxhome.com/file/2023/4/70094_0s.jpg)
详解Python如何使用Netmiko进行文件传输
2021-06-20 19:49:17
![](https://img.aspxhome.com/file/2023/7/68337_0s.png)
解密CSS Sprites:技巧、工具和教程
2011-01-11 19:38:00
![](https://img.aspxhome.com/file/UploadPic/20111/11/pokemon-29s.gif)
ASP中使用SQL语句教程
2008-09-03 12:17:00
js 数值项目的格式化函数代码
2023-07-14 16:51:31
10行Python代码助你整理杂乱无章的文件
2021-03-08 21:11:12
django celery redis使用具体实践
2022-12-03 02:45:39
![](https://img.aspxhome.com/file/2023/5/87785_0s.png)
SQL事务用法begin tran,commit tran和rollback tran的用法
2012-01-05 18:58:51
对网页切片算法问题的研究
2008-06-05 12:41:00