python - 如何在需要时退出循环?
问题描述
我与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
. 然后在外壳/终端中,只需执行以下操作:
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 - 增量写入结果
第三种方法是打开您的结果文件以在循环内追加并添加每个可用的新结果,而不是等到结束。
我对您的算法知之甚少,不知道这是否适合您。
我仍然不是 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 程序员有任何意见,我很乐意学习。
推荐阅读
- zerobrane - 在 zerobrane 的交互式解释器中,math.maxinteger 值为零
- html - bootstrap navbar-toggler 按钮单击将列表项颜色和大小更改为默认值一秒钟?
- python - 我怎样才能把这个 Python 代码变成一个函数?
- python - tkinter 文件目录保存输出
- xaml - 在图像文件名中使用限定符在 UWP 运行时不起作用
- wordpress - 无法为我的 Wordpress 网站更新 siteurl 和 home
- python - Python迭代器在数据框或带有股票数据的列表上
- sql-server - 使用 AVG 和 MAX 更新 SQL Server
- python - 从列中删除 NaN 值时会发生什么?
- python - 在 EC2 实例 (AWS) 上使用 Bash 脚本导入错误加载模块