栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

功能超时(Windows)?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

功能超时(Windows)?

我认为解决此问题的一种好方法是创建一个装饰器并使用该

Thread.join(timeout=seconds)
方法。请记住,没有杀死线程的好方法,因此只要您的程序正在运行,它就会或多或少在后台继续运行。

首先,创建一个这样的装饰器:

from threading import Threadimport functoolsdef timeout(timeout):    def deco(func):        @functools.wraps(func)        def wrapper(*args, **kwargs): res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, timeout))] def newFunc():     try:         res[0] = func(*args, **kwargs)     except Exception as e:         res[0] = e t = Thread(target=newFunc) t.daemon = True try:     t.start()     t.join(timeout) except Exception as je:     print ('error starting thread')     raise je ret = res[0] if isinstance(ret, baseException):     raise ret return ret        return wrapper    return deco

然后,执行以下操作:

func = timeout(timeout=16)(MyModule.MyFunc)try:    func()except:    pass #handle errors here

您可以在需要的任何地方使用此装饰器,例如:

@timeout(60)def f():    ...


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号