【问题标题】:How to run time.sleep() without stopping while loop如何在不停止 while 循环的情况下运行 time.sleep()
【发布时间】:2021-09-21 11:49:43
【问题描述】:

有没有办法在不干扰循环的情况下从无限循环中调用具有 wait(time.sleep()) 的函数? 我正在尝试运行一些需要等待几秒钟的任务,但问题是当等待过程发生时while循环也会停止。 这是我尝试过的- 这是我的代码:

import cv2
import time

def waiting():
    print("Inside function")
    # Running Some Tasks
    time.sleep(5)
    print("Done sleeping")


def main():
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        cv2.imshow("Webcam", frame)

        k = cv2.waitKey(10)
        if k == 32:  # Press SPACEBAR for wait function
            waiting()
        elif k == 27:  # Press ESC to stop code
            break
    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()

【问题讨论】:

    标签: python-3.x async-await parallel-processing opencv-python


    【解决方案1】:

    您目前正在使用单线程脚本。您应该使用threadingmultiprocessing。这使得(看起来)多个进程处于活动状态。取决于您使用的是threading 还是multiprocessing

    【讨论】:

    • 谢谢你的建议,我去看看。感谢您的时间。
    • @git-ruthvik 告诉我进展如何。祝你好运!
    【解决方案2】:

    您应该使用线程。看起来计算机正在同时执行这两项操作。

    import threading
    
    t = threading.Thread(target=function)
    t.start()
    

    【讨论】:

    • 感谢您的意见,成功了!
    • 抱歉@cris 是这个平台的新手
    【解决方案3】:

    感谢@JLT 和@TerePiim 的快速回复。以下是可能从中受益的任何人的更新代码:

    import cv2
    import time
    import threading
    
    
    def waiting():
        print("Inside parallel function")
        # Running some Tasks
        time.sleep(5)
        print("Done sleeping")
    
    
    def main():
        cap = cv2.VideoCapture(0)
        while True:
            ret, frame = cap.read()
            cv2.imshow("Webcam", frame)
            k = cv2.waitKey(10)
            if k == 32:  # Press SPACEBAR for wait function
                t = threading.Thread(target=waiting)
                t.start()
    
            elif k == 27:  # Press ESC to stop code
                break
        cap.release()
        cv2.destroyAllWindows()
    
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 1970-01-01
      • 2021-03-12
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 2012-03-01
      相关资源
      最近更新 更多