gpt4 book ai didi

Python - 做一些事情直到按键或超时

转载 作者:太空狗 更新时间:2023-10-29 20:27:43 25 4
gpt4 key购买 nike

我几乎已经解决了这个问题,但我认为我需要朝着正确的方向插入。

我想每五秒执行一次操作,直到 已经过去了一定的时间,或者用户中断了它(在这种情况下它完成了循环的迭代在完成之前)。

import time
import threading

def do_something():
T0 = time.clock()
while (time.clock() - T0) < 60 and not e.isSet(): #as long as 60s haven't elapsed
#and the flag is not set
#here do a bunch of stuff
time.sleep(5)

thread = threading.Thread(target=do_something, args=())
thread.start()
e = threading.Event()

while thread.isAlive():
#here I want the main thread to wait for a keypress and, if it receives it,
#set the event e, which will cause the thread to finish its work.

我不知道如何让最后一行工作。在循环内使用 raw_input() 将阻塞,直到用户点击回车,无论线程是否完成其工作。是否有另一个模块可以满足我的要求?

编辑:我使用的是 Windows XP。

最佳答案

您可以使用 thread.interrupt_main() .


示例:

import thread
import time
import threading

e = threading.Event()

def main():
thread.start_new_thread(wait_for_input, tuple())
thread.start_new_thread(do_something, tuple())

def wait_for_input():
raw_input()
e.set()

def do_something():
T0 = time.clock()
while (time.clock() - T0) < 60 and not e.isSet(): #as long as 60s haven't elapsed
#and the flag is not set
#here do a bunch of stuff
time.sleep(5)
thread.interrupt_main() # kill the raw_input thread

try:
thread.start_new_thread(main, tuple())
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
pass

关于Python - 做一些事情直到按键或超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com