我使用 R-Pi
和 cam
。我已经编写了一个多小时迭代过程的代码。
import numpy as np
import cv2
import time
ret, frame = cam0.read()
timecheck = time.time()
future = 60
runNo = 0
while ret:
if time.time() >= timecheck:
ret, frame = cam0.read()
#Do something here
timecheck = time.time()+future
runNo=runNo+1
if(runNo> 60):
break
else:
ret = cam0.grab()
#save log as .txt file
with open("acc_list.txt", "w") as output:
output.write(str(acc_list))
但有时,完成工作只需要不到一个小时。我想在 runNo
达到 60
之前退出迭代。因为我必须保存 acc_list.txt
文件,所以我不能直接关闭程序。
如果是视频流,我会用这个:
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
但是我在将其修改为我的代码时遇到了错误。
有什么好的方法吗?
最佳答案
有很多可能的方法,有些更干净,有些更脏 :-)
没有特别的顺序,这里有一些。我可能会为它们添加代码,因为我有空闲时间来正确解释它们。
方法 1 - 使用哨兵文件
一个简单的(“hacky”)方法是检查循环内部是否存在名为 stop
的文件.然后在 shell/Terminal 中,只需执行以下操作:
touch stop
程序将退出。如果你碰巧使用 bash
,您只需键入:
> stop
记得删除名为stop
的文件在程序的开头和结尾。
我不是 Python 程序员,但这很有效:
#!/usr/local/bin/python3
import os
from time import sleep
# Remove any sentinel "stop" files from previous runs
def CleanUp():
try:
os.remove('stop')
except:
pass
CleanUp()
runNo=0
while True:
print("Running...")
sleep(1)
if runNo>60 or os.path.exists('stop'):
break
runNo=runNo+1
print("Writing results")
CleanUp()
方法 2 - 使用第二个线程
另一种方法是启动第二个线程,该线程从终端进行阻塞读取,当用户输入内容时,它会设置一个标志,主线程通过其循环在每次迭代中检查该标志,就像它检查一样runNo
.
这表明:
#!/usr/local/bin/python3
import threading
import os
from time import sleep
ExitRequested=False
def InputHandlerThread():
global ExitRequested
s=input('Press Enter/Return to exit\n')
print("Exit requested")
ExitRequested=True
# Start user input handler - start as daemon so main() can exit without waiting
t=threading.Thread(target=InputHandlerThread,daemon=True)
t.start()
runNo=0
while True:
print('runNo: {}'.format(runNo))
sleep(1)
if runNo>60 or ExitRequested:
break
runNo=runNo+1
print("Writing results")
这可能不适用于 OpenCV,因为 imshow()
函数以某种方式使用 waitKey()
中的空闲时间(以毫秒 参数给出)功能来更新屏幕。如果你调用imshow()
你会看到这个没有任何后续waitKey()
- 屏幕上不会出现任何内容。
因此,如果您使用的是 imshow()
你必须使用 waitKey()
这会干扰在第二个线程中读取键盘。如果是这种情况,请使用其他方法之一。
方法 3 - 增量写入结果
第三种方法是在循环内打开结果文件for append,并在每个新结果可用时添加它,而不是等到结束。
我对您的算法了解不多,无法确定这是否适合您。
我仍然不是 Python 程序员,但这行得通:
#!/usr/local/bin/python3
import os
from time import sleep
runNo=0
while True:
print("Running...")
# Append results to output file
with open("results.txt", "a") as results:
results.write("Result {}\n".format(runNo))
sleep(1)
if runNo>60:
break
runNo=runNo+1
方法 4 - 使用信号
第四种方法是设置一个信号处理程序,当它接收到信号时,它会设置一个标志,主循环在每次迭代时检查该标志。然后在终端中使用:
pkill -SIGUSR1 yourScript.py
这是一些工作代码:
#!/usr/local/bin/python3
import signal
import os
from time import sleep
def handler(signum,stack):
print("Signal handler called with signal ",signum)
global ExitRequested
ExitRequested=True
ExitRequested=False
# Install signal handler
signal.signal(signal.SIGUSR1,handler)
runNo=0
while True:
print('runNo: {} Stop program with: "kill -SIGUSR1 {}"'.format(runNo,os.getpid()))
sleep(1)
if runNo>60 or ExitRequested:
break
runNo=runNo+1
print("Writing results")
示例输出
runNo: 0 Stop program with: "kill -SIGUSR1 16735"
runNo: 1 Stop program with: "kill -SIGUSR1 16735"
runNo: 2 Stop program with: "kill -SIGUSR1 16735"
runNo: 3 Stop program with: "kill -SIGUSR1 16735"
runNo: 4 Stop program with: "kill -SIGUSR1 16735"
runNo: 5 Stop program with: "kill -SIGUSR1 16735"
runNo: 6 Stop program with: "kill -SIGUSR1 16735"
runNo: 7 Stop program with: "kill -SIGUSR1 16735"
Signal handler called with signal 30
Writing results
讨论
YMMV,但我的感觉是方法 3 是最干净的,而方法 1 是最大的 hack。方法 2 可能最接近您的要求,我采用了方法 4(以及所有其他方法),因此我可以学到一些东西。
如果有真正的 Python 程序员有任何意见,我很乐意学习。
关于python - 如何在需要时退出循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50479068/