Home > Software engineering >  How to run time.sleep() without stopping while loop
How to run time.sleep() without stopping while loop

Time:09-22

Is there a way to call a function which has wait(time.sleep()) from infinite while loop without disturbing the loop? I am trying to run a few task that require to wait for a few seconds but the issue is that the while loop also stops when the wait process is happening. This is what I have tried out- Here is my code:

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()

CodePudding user response:

You should use threads. It will look like the computer is doing them both at the same time.

import threading

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

CodePudding user response:

You are working in a single thread script at the moment. You should use threading or multiprocessing. This makes (it look like) multiple processes (are) active. Dependent on if you use threading or multiprocessing.

CodePudding user response:

Thanks for the quick responses from @JLT and @TerePiim. Here is the updated code for anyone who might benefit from this:

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()
  • Related