Python 如何手动结束正在收集数据的无限 while 循环,而不结束代码并且不使用键盘中断?



在我的代码中,我有一个"while True:"循环,在收集实时数据(3-5小时(时需要运行不同的时间。由于时间不是预先确定的,我需要在不终止脚本的情况下手动结束 while 循环,以便它可以继续到脚本中的下一个代码体。

不想在循环结束时使用"input((",因为那样我必须手动告诉它每次完成循环时继续循环,我正在收集实时数据到半秒,所以这是不切实际的。

我也不想使用键盘中断,遇到了问题。还有其他解决方案吗?我所看到的只是尝试/除了"键盘中断"

def datacollect()
def datacypher()
while True:
    #Insert code that collects data here
    datacollect()
#end the while loop and continue on
#this is where i need help
datacypher()
print('Yay it worked, thanks for the help')

我希望手动结束循环,然后继续执行作用于收集的数据的代码。

如果您需要更多详细信息或对我的措辞有疑问,请告诉我。我以前只问过一个问题。我在学习。

在第二个线程中添加密钥侦听器怎么样?按 Enter 后,您将通过共享布尔值手动将脚本移动到下一阶段。第二个线程不应该减慢进程的速度,因为它会在input()上阻塞。

from threading import Thread
from time import sleep
done = False
def listen_for_enter_key_press():
    global done
    input()
    done = True
listener = Thread(target=listen_for_enter_key_press)
listener.start()
while not done:
    print('working..')
    sleep(1)
listener.join()
print('Yay it worked, thanks for the help')

中断循环的一种方法是使用信号。

import signal
def handler(signum, stackframe):
    global DONE
    DONE = True
signal.signal(signal.SIGUSR1, handler)
DONE = False
while not DONE:
    datacollect()
datacypher()

循环将继续,直到程序收到 USR1 信号(例如,通过 kill -s USR1 <pid> 发送,其中<pid>是程序的进程 ID(,此时DONE将在下次循环测试其值时True

您只需将handler安装为signal.SIGINT而不是signal.SIGUSR1的处理程序即可将其适应键盘中断,因为默认信号处理程序首先会引发KeyboardInterrupt异常。

一种选择是,您可以查找文件的存在,例如:

import os.path
fname = '/tmp/stop_loop'
def datacollect()
def datacypher()
while not os.path.isfile(fname):
    #Insert code that collects data here
    datacollect()
#end the while loop and continue on
#this is where i need help
datacypher()
print('Yay it worked, thanks for the help')

如果该文件不存在,它将继续通过 while 循环。 然后,当你想停止while循环时,你可以只做touch /tmp/stop_loop,while循环就会停止。

我怀疑isfile()应该是一个相当有效的,所以也许这不会太糟糕。

最新更新