如何在不停止 while 循环的情况下 运行 time.sleep()
How to run time.sleep() without stopping while loop
有没有一种方法可以在不干扰循环的情况下从无限 while 循环中调用具有 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()
你应该使用线程。看起来计算机正在同时执行这两项操作。
import threading
t = threading.Thread(target=function)
t.start()
您目前正在单线程脚本中工作。你应该使用 threading or multiprocessing. This makes (it look like) multiple processes (are) active. Dependent on if you use threading or multiprocessing.
感谢@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()
有没有一种方法可以在不干扰循环的情况下从无限 while 循环中调用具有 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()
你应该使用线程。看起来计算机正在同时执行这两项操作。
import threading
t = threading.Thread(target=function)
t.start()
您目前正在单线程脚本中工作。你应该使用 threading or multiprocessing. This makes (it look like) multiple processes (are) active. Dependent on if you use threading or multiprocessing.
感谢@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()