python使用装饰器和线程限制函数执行时间的方法

yipeiwu_com6年前Python基础

本文实例讲述了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读取和保存图片5种方法对比

python读取和保存图片5种方法对比 python中对象之间的赋值是按引用传递的,如果需要拷贝对象,需要用到标准库中的copy模块 方法一:利用 PIL 中的 Image 函数 这个函...

Python使用CMD模块更优雅的运行脚本

本文实例讲述了Python使用CMD模块更优雅的运行脚本的方法。分享给大家供大家参考。具体分析如下: 平时由于经常给测试人员调试一些东西,虽然写了一些脚本,感觉还是不方便。 python...

Tensorflow 查看变量的值方法

定义一个变量,直接输出会输出变量的属性,并不能输出变量值。那么怎么输出变量值呢?请看下面得意 import tensorflow as tf biases=tf.Variable(...

python开头的coding设置方法

缘起: [root@CentOS7 code]# python multi_thread_mfw.py File "multi_thread_mfw.py", line 138...

Python学习小技巧之列表项的拼接

本文介绍的是关于Python实现列表项拼接的一个小技巧,分享出来供大家参考学习,下面来看看详细的介绍: 典型代码: data_list = ['a', 'b', 'c', 'd',...