在我的代码中,我有一个"while:“循环,它需要在收集实时数据(3-5小时)时运行不同的时间。由于时间不是预先确定的,所以我需要手动结束while循环而不终止脚本,这样它就可以继续到脚本中的下一个代码体。
我不想在循环结束时使用“not ()”,因为在每次循环结束时,我必须手动告诉它继续循环,我将实时数据收集到半秒,所以这是不切实际的。
我也不想用键盘中断,已经有问题了。还有其他解决办法吗?我所看到的只是尝试/除了用“键盘中断”
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')
我希望手动结束循环,然后继续对所收集的数据进行操作的代码。
如果您需要更多的细节或对我的措辞有问题,请告诉我。我以前只问过一个问题。我在学习。
发布于 2019-06-14 17:23:18
中断循环的一种方法是使用信号。
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
异常。
发布于 2019-06-14 17:08:46
一种选择是,您可以查找文件的存在,例如:
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()
应该是一个相当有效率的,所以也许这不会太糟糕。
https://stackoverflow.com/questions/56602412
复制相似问题