我正在调用Python中的一个函数,我知道该函数可能会停止并迫使我重新启动脚本.
我该如何调用该函数,或者如何包装它,以便在需要5秒以上的时间时,脚本取消该函数并执行其他操作?
我正在调用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
在调用signal.alarm(10)
后10秒,处理程序被调用.这会引发一个异常,您可以从常规Python代码中截获该异常.
这个模块不能很好地处理线程(但是,谁能呢?)
Note that由于我们在超时发生时引发异常,它可能最终会在函数中被捕获并忽略,例如一个这样的函数:
def loop_forever():
while 1:
print('sec')
try:
time.sleep(10)
except:
continue