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


Posted in Python onApril 18, 2015

本文实例讲述了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 相关文章推荐
Python对象转JSON字符串的方法
Apr 27 Python
Python运算符重载详解及实例代码
Mar 07 Python
在python中使用正则表达式查找可嵌套字符串组
Oct 24 Python
Python输出由1,2,3,4组成的互不相同且无重复的三位数
Feb 01 Python
用十张图详解TensorFlow数据读取机制(附代码)
Feb 06 Python
python+ffmpeg视频并发直播压力测试
Mar 06 Python
对python中的xlsxwriter库简单分析
May 04 Python
pandas DataFrame 根据多列的值做判断,生成新的列值实例
May 18 Python
Centos 升级到python3后pip 无法使用的解决方法
Jun 12 Python
python tkinter库实现气泡屏保和锁屏
Jul 29 Python
python自动发微信监控报警
Sep 06 Python
面向对象学习之pygame坦克大战
Sep 11 Python
python使用multiprocessing模块实现带回调函数的异步调用方法
Apr 18 #Python
python对指定目录下文件进行批量重命名的方法
Apr 18 #Python
python开启多个子进程并行运行的方法
Apr 18 #Python
C#返回当前系统所有可用驱动器符号的方法
Apr 18 #Python
python关闭windows进程的方法
Apr 18 #Python
python使用Queue在多个子进程间交换数据的方法
Apr 18 #Python
python获取当前计算机cpu数量的方法
Apr 18 #Python
You might like
如何突破PHP程序员的技术瓶颈分析
2011/07/17 PHP
新浪微博OAuth认证和储存的主要过程详解
2015/03/27 PHP
PHP与Perl之间知识点区别整理
2019/03/19 PHP
在jQuery1.5中使用deferred对象 着放大镜看Promise
2011/03/12 Javascript
js实现文本框中输入文字页面中div层同步获取文本框内容的方法
2015/03/03 Javascript
Bootstrap+jfinal退出系统弹出确认框的实现方法
2016/05/30 Javascript
AngularJS使用ng-inlude指令加载页面失败的原因与解决方法
2017/01/19 Javascript
JS SetInterval 代码实现页面轮询
2017/08/11 Javascript
JS实现图片居中悬浮效果
2017/12/25 Javascript
vue打包相关细节整理(小结)
2018/09/28 Javascript
浅谈发布订阅模式与观察者模式
2019/04/09 Javascript
Vue实现渲染数据后控制滚动条位置(推荐)
2019/12/09 Javascript
antd多选下拉框一行展示的实现方式
2020/10/31 Javascript
[47:45]Liquid vs OG 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
python中map、any、all函数用法分析
2015/04/21 Python
总结Python编程中函数的使用要点
2016/03/20 Python
Linux下通过python访问MySQL、Oracle、SQL Server数据库的方法
2016/04/23 Python
python3中str(字符串)的使用教程
2017/03/23 Python
python模拟登陆,用session维持回话的实例
2018/12/27 Python
pycharm远程开发项目的实现步骤
2019/01/20 Python
Python 使用 PyMysql、DBUtils 创建连接池提升性能
2019/08/14 Python
tensorflow 自定义损失函数示例代码
2020/02/05 Python
使用py-spy解决scrapy卡死的问题方法
2020/09/29 Python
python 实现aes256加密
2020/11/27 Python
基于注解实现 SpringBoot 接口防刷的方法
2021/03/02 Python
使用javascript和HTML5 Canvas画的四渐变色播放按钮效果
2014/04/10 HTML / CSS
HTML5未来发展趋势
2016/02/01 HTML / CSS
阿里巴巴Oracle DBA笔试题答案-备份恢复类
2013/11/20 面试题
追悼会子女答谢词
2014/01/28 职场文书
小学生美德少年事迹
2014/02/02 职场文书
教师试用期自我鉴定
2014/02/12 职场文书
党员党性分析材料
2014/02/17 职场文书
应届生求职信范文
2014/06/30 职场文书
建议书的格式及范文
2015/09/14 职场文书
Python道路车道线检测的实现
2021/06/27 Python
CentOS下安装Jenkins的完整步骤
2022/04/07 Servers