Python:在循环中只打印一次

ukxgm1gy  于 2023-02-18  发布在  Python
关注(0)|答案(7)|浏览(309)

我有一个代码,我想从相机捕捉视频。我想使用Python的日志库来获取shell上的消息或将其导出到文本文件。
下面是我的代码的一部分,在while循环中我想打印 Camera Opened Successfully

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)

但我在壳里得到的是这样的

直到我终止了运行脚本。有什么想法如何使它只打印一次。

q43xntqr

q43xntqr1#

你必须打破这个循环

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
ajsxfq5m

ajsxfq5m2#

您需要中断while循环,同样由于您希望在ret为True时立即中断循环,因此可以用途:

ret = False
while not ret:

    ret, image = cap.read()

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

oxiaedzo3#

设置一个标志以触发日志,然后将其设置为false。当准备退出循环时,将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
anauzrmj

anauzrmj4#

另一种可能性是利用Python中默认的可变参数:

def print_once(string, bucket=[]):
    """
    Print only one time

    >>> print_once("foo")
    foo
    >>> print_once("foo")
    """
    if string not in bucket:
        print(string)
        bucket.append(string)
smdnsysy

smdnsysy5#

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

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
6ie5vjzr

6ie5vjzr6#

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的答案操作。此选项将在循环中继续,并且只打印一次。

62o28rlo

62o28rlo7#

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

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

相关问题