Python: 循环内只打印一次

Python: Print only one time inside a loop

我有一个代码,我想从相机中捕捉视频。我想使用 Python 的日志记录库在 shell 上获取消息或将它们导出到文本文件。

这是我的代码的一部分,我想在 while 循环中打印 相机成功打开

import numpy as np
import cv2
import logging as log

cap = cv2.VideoCapture('5.mpg')

while True:

    ret, image = cap.read()

    if ret == True:
        log.warning('Camera Opened Successfully')

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    clahe = cv2.createCLAHE(clipLimit = 15.0, tileGridSize=(8,8))
    gray1 = clahe.apply(gray)

但是我在 shell 中得到的是这样的:

直到我终止了 运行 脚本。关于如何让它只打印一次的任何想法。

你必须跳出循环

import numpy as np
import cv2
import logging as log

cap = cv2.VideoCapture('5.mpg')

while True:

    ret, image = cap.read()

    if ret == True:
        log.warning('Camera Opened Successfully')
        break
import numpy as np
import cv2
import logging as log

cap = cv2.VideoCapture('5.mpg')
hasOpened = False

while True:

    ret, image = cap.read()

    if ret and not hasOpened:
        log.warning('Camera Opened Successfully')
        hasOpened = True

如果您想在打印后跳出循环,请按照 Matt 的回答进行操作。这个选项会一直循环下去,只打印一次。

添加一个额外的布尔值来跟踪您之前是否打印过它:

import numpy as np
import cv2
import logging as log

cap = cv2.VideoCapture('5.mpg')
printed = False

while True:

    ret, image = cap.read()

    if ret == True and not printed:
        log.warning('Camera Opened Successfully')
        printed = True

假设你想用你的主循环来处理你的应用程序逻辑,并且用一个循环来检测它是否打开而另一个循环来处理它是没有意义的,那么我想你想要的是设置一个变量来确定状态是否已经改变。

import numpy as np
import cv2
import logging as log

cap = cv2.VideoCapture('5.mpg')
old_ret = False

while True:

    ret, image = cap.read()

    if old_ret == False and ret == True:
        old_red = True
        log.warning('Camera Opened Successfully')

    if ret == True:
        # Do other things that need the camera but no log

你需要打破 while 循环,因为你想在得到 ret True 后立即跳出循环,你可以使用:

ret = False
while not ret:

    ret, image = cap.read()

    if ret:
        log.warning('Camera Opened Successfully')
    # any other code

设置一个标志来触发日志,然后将其设置为假。当您准备好退出循环时,ret 将变为 False 以便它退出

import numpy as np
import cv2
import logging as log

cap = cv2.VideoCapture('5.mpg')
ret = True
logit = True
while ret:

    ret, image = cap.read()

    if logit == True:
        log.warning('Camera Opened Successfully')
        logit = False

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    clahe = cv2.createCLAHE(clipLimit = 15.0, tileGridSize=(8,8))
    gray1 = clahe.apply(gray)
    // process remainder of situation setting