Python 超时功能,如果需要的时间太长
原谅我,我是个新手。我调查了一些解决办法。但我很难理解和修改这一点。(或者可能没有符合我想象的解决方案?)。我希望它能在Ubuntu和Win7上运行 有这样一个例子Python 超时功能,如果需要的时间太长,python,python-2.7,function,Python,Python 2.7,Function,原谅我,我是个新手。我调查了一些解决办法。但我很难理解和修改这一点。(或者可能没有符合我想象的解决方案?)。我希望它能在Ubuntu和Win7上运行 有这样一个例子 import random,time def example(): while random.randint(0,10) != 1: time.sleep(1) print "down" example() 我的想象是 如果example()的运行时间超过10秒,请再次运行example()。(
import random,time
def example():
while random.randint(0,10) != 1:
time.sleep(1)
print "down"
example()
我的想象是
如果example()的运行时间超过10秒,请再次运行example()。(也许有一个地方我可以编写任何其他代码。就像我想在TXT上记录超时事件一样,我可以在那个地方编写代码。)
否则,什么也不做
有可能做到这一点吗?我不确定我是否完全理解您想要实现的目标,但由于您一直在循环,并且只有一个简短且可预测的阻塞命令,您可以简单地存储循环开始的时间,然后在每次循环迭代时将其与当前时间进行一次比较。如果差异超过您的限制,请执行您想要的任何操作:
import random,time
time_limit=10
def example():
time_start = time.time() # store current time (seconds since 1970)
while random.randint(0,10) != 1:
time.sleep(1)
if (time.time() >= time_start + time_limit): # compare with current time
print "canceled!"
break # break the while-loop
print "down"
example()
您可以在一个单独的线程中运行看门狗,当主线程超过时间限制时,它会中断主线程(运行<代码>示例代码>)。以下是一个可能的实现,为便于调试,将超时降低到3s:
import time, threading, thread
def watchdog_timer(state):
time.sleep(3)
if not state['completed']:
thread.interrupt_main()
def run_example():
while True:
state = {'completed': False}
watchdog = threading.Thread(target=watchdog_timer, args=(state,))
watchdog.daemon = True
watchdog.start()
try:
example()
state['completed'] = True
except KeyboardInterrupt:
# this would be the place to log the timeout event
pass
else:
break
谢谢你的帮助。这就是我想要的解决方案。