在前面之前的博客,我们看了Python 装饰器的说明:
Python 装饰器 说明
https://www.cndba.cn/dave/article/3090
Python 多线程与多进程 概念和操作示例
https://www.cndba.cn/dave/article/2155
我们可以通过Python 装饰器和线程来限制函数的执行时间。如果执行完成则返回函数正常的返回值,如果执行超时则会抛出错误信息。
# -*- 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 dave(secs):
time.sleep(secs)
print "My Blog is: http://www.cndba.cn/dave"
return 'Finished'
if __name__ == "__main__":
print dave(4)
版权声明:本文为博主原创文章,未经博主允许不得转载。
- 上一篇:Python 装饰器 说明
- 下一篇:Linux Htop 工具说明