超时函数(windows)? [英] Timeout a function (windows)?

查看:49
本文介绍了超时函数(windows)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为特定功能实现超时.我已经检查了 SE 中的许多问题,但找不到任何适合我的问题的解决方案,因为:

I am trying to implement timeout for a particular function. I have checked many of the questions in SE and couldn't find any solution which fits my problem, because:

  1. 我在 Windows 中运行 python
  2. 超时应用于我无法控制的 python 函数,即它是在已经设计好的模块中定义的.
  3. python 函数不是子进程

我已经为特定任务开发了一个已经设计好的自定义模块(比如 MyModule),其中定义了一些函数.由于外部因素,其中一个函数(比如 MyFunc)有永远运行的趋势,我只是不希望 python 脚本挂起.

I am having a already designed custom module (say MyModule) developed for particular tasks, and there are functions defined in it. One of the function (say MyFunc) has a tendency to run forever because of external factors, and I just don't want the python script to hang.

我打算添加一个超时功能,如下伪代码所示:

I am planning to add a timeout feature, as said below pseudocode:

import MyModule

set_timeout(T)
MyResult=MyModule.MyFunc()

#Come to this part of script after execution of MyFunc() or after T seconds (the latter on priority)
if Timeout occurred:
    print 'MyFunc did not execute completely'
else:
    print 'MyFunc completed'

但我不确定可以使用哪个模块在 python 上实现这一点.请注意,我是新手,我写的所有脚本都是直接基于 SE Answers 或 Python 文档.

But I am not sure which module can be used to achieve this on python. Note that I am a newbie, and all the scripts I have written are directly based on SE Answers or Python Documentation.

推荐答案

我认为解决这个问题的一个好方法是创建一个装饰器并使用 Thread.join(timeout=seconds) 方法.请记住,没有杀死线程的好方法,因此只要您的程序正在运行,它就会或多或少地继续在后台运行.

I think a good way to approach this is to create a decorator and use the Thread.join(timeout=seconds) method. Bear in mind that there's no good way to kill the thread, so it will continue to run in the background, more or less, as long as your program is running.

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

First, create a decorator like this:

from threading import Thread
import functools

def 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

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

You can use this decorator anywhere you need with something like:

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

这篇关于超时函数(windows)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆