简体   繁体   English

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

[英]Timeout function if it takes too long

Forgive me, I am a newbie. 原谅我,我是新手。 I've surveyed some solution. 我已经调查了一些解决方案。 But it is so hard for me to understand and to modify that. 但是,我很难理解和修改它。 (Or maybe there is no solution in line with my imagination?). (或者也许没有符合我的想象的解决方案?)。 And I hope it can work on Ubuntu & Win7. 我希望它可以在Ubuntu和Win7上运行。

There is an example like this. 有一个这样的例子。

import random,time

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

example()

And my imagination is... 我的想象力是

If, the example() run over 10s, then rerun the example() again. 如果exam​​ple()运行了10秒钟以上,则再次重新运行example()。 (And maybe there is a place I can code anything else. Like I want to record the timeout event on TXT, and I can code the code at that place.) Else, do nothing. (也许还有一个地方,我可以编码其他东西。就像我想在TXT上记录超时事件一样,我可以在那个地方编码。)否则,什么也不做。

Is it possible to do that? 有可能这样做吗?

You can run a watch-dog in a separate thread that interrupts the main thread (that runs example ) when it exceeds the time limit. 您可以在单独的线程中运行看门狗,当它超过时间限制时,该线程会中断主线程(运行example )。 Here is a possible implementation, with timeout lowered to 3s for ease of debugging: 这是一个可能的实现,为了简化调试,超时降低到了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

I'm not sure if I fully understood what you want to achieve, but as you're constantly looping and only have one short and predictable blocking command, you could simply store the time when the loop started and then compare it to the current time once per loop iteration. 我不确定我是否完全了解您要实现的目标,但是由于您不断循环,并且只有一个简短且可预测的阻塞命令,因此您可以简单地存储循环开始的时间,然后将其与当前时间进行比较每个循环迭代一次。 If the difference exceeds your limit, do whatever you want: 如果差异超出限制,请执行以下操作:

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