繁体   English   中英

超时功能(如果花费太长时间)

[英]Timeout function if it takes too long

原谅我,我是新手。 我已经调查了一些解决方案。 但是,我很难理解和修改它。 (或者也许没有符合我的想象的解决方案?)。 我希望它可以在Ubuntu和Win7上运行。

有一个这样的例子。

import random,time

def example():
    while random.randint(0,10) != 1:
        time.sleep(1)
    print "down"

example()

我的想象力是

如果exam​​ple()运行了10秒钟以上,则再次重新运行example()。 (也许还有一个地方,我可以编码其他东西。就像我想在TXT上记录超时事件一样,我可以在那个地方编码。)否则,什么也不做。

有可能这样做吗?

您可以在单独的线程中运行看门狗,当它超过时间限制时,该线程会中断主线程(运行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

我不确定我是否完全了解您要实现的目标,但是由于您不断循环,并且只有一个简短且可预测的阻塞命令,因此您可以简单地存储循环开始的时间,然后将其与当前时间进行比较每个循环迭代一次。 如果差异超出限制,请执行以下操作:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM