我怎么能在我想要的时候退出循环呢?

2024-06-06 21:15:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用R-Picam。我已经编写了一段代码,可以在一个小时内迭代这个过程。你知道吗

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

但是我在修改代码时遇到了错误。你知道吗

有什么好办法吗?你知道吗


Tags: 代码importtxtreadiftimeasframe
1条回答
网友
1楼 · 发布于 2024-06-06 21:15:01

有很多可能的方法,有些更干净,有些更脏:-)

没有特别的顺序,这里有一些。我可能会为它们添加代码,因为我会利用空闲时间对它们进行适当的解释。你知道吗


方法1-使用sentinel文件

要做到这一点,一个简单的方法是在循环内部检查名为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-增量写入结果

第三种方法是在循环中打开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

documentation on signals.

以下是一些工作代码:

#!/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

讨论

但是我觉得方法3是最干净的,方法1是最大的漏洞。方法2可能与你要求的最接近,我做了方法4(事实上还有其他方法),所以我可以学到一些东西。你知道吗

如果任何真正的Python程序员有什么意见,我很乐意学习。你知道吗

相关问题 更多 >