一个函数调用超时

问题:

我在Python中调用一个函数,我知道可能会停止并强制我重新启动脚本。
如何调用该函数或将其包装到哪里,以便如果需要超过5秒的脚本取消它并执行其他操作?

回答:

如果您在UNIX上运行,可以使用signal包:

In [1]: import signal

# Register an handler for the timeout
In [2]: def handler(signum, frame):
   ...:     print "Forever is over!"
   ...:     raise Exception("end of time")
   ...: 

# This function *may* run for an indetermined time...
In [3]: def loop_forever():
   ...:     import time
   ...:     while 1:
   ...:         print "sec"
   ...:         time.sleep(1)
   ...:         
   ...:         

# Register the signal function handler
In [4]: signal.signal(signal.SIGALRM, handler)
Out[4]: 0

# Define a timeout for your function
In [5]: signal.alarm(10)
Out[5]: 0

In [6]: try:
   ...:     loop_forever()
   ...: except Exception, exc: 
   ...:     print exc
   ....: 
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time

# Cancel the timer if the function returned before timeout
# (ok, mine won't but yours maybe will 🙂
In [7]: signal.alarm(0)
Out[7]: 0

调用alarm.alarm(10) 10秒后,调用处理程序。这引发了一个例外,您可以从常规Python代码拦截。
这个模块不能很好地与线程(但是,谁呢?)
 注意,因为在超时发生时引发异常,它可能会在函数内部被捕获和忽略,例如一个这样的函数:

def loop_forever():
    while 1:
        print 'sec'
        try:
            time.sleep(10)
        except:
            continue

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Timeout on a function call

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 1 = 6