[英]Stop a while loop by escape key?
我編輯了問題,因為現在當我在Pycharm(IN Powershell)外部運行代碼時,鍵盤中斷可以正常工作,但是現在我正在努力在Escape鍵上終止代碼。
from PIL import ImageGrab
import numpy as np
import cv2
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
def record_screen():
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('ResultFile.avi', fourcc, 25.0, screensize)
while True:
try:
img = ImageGrab.grab()
img_np = np.array(img)
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
out.write(frame)
print('recording....')
except KeyboardInterrupt:
break
out.release()
cv2.destroyAllWindows()
record_screen()
不幸的是,除非您希望循環的每次迭代都需要一個按鍵,否則很難聽到按鍵的聲音,這對於您的工作是不切實際的。 我認為Joel的評論正確無誤,您應該使用
Ctrl + C
並像這樣捕獲KeyboardInterrupt
from PIL import ImageGrab
import numpy as np
import cv2
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
def record_screen():
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('ResultFile.avi', fourcc, 25.0, screensize)
while True:
try:
img = ImageGrab.grab()
img_np = np.array(img)
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
out.write(frame)
print('recording....')
except KeyboardInterrupt:
break
out.release()
cv2.destroyAllWindows()
record_screen()
這樣, KeyboardInterrupt
不會終止程序,它只會結束while循環,從而使您可以釋放cv2
並清理其余的cv2
資源。
由於您將PyCharm用作IDE,因此Ctrl + C可能對您不起作用-嘗試使用Ctrl + F2 。
您應該創建一個名為running的變量! 在while循環之前設置“ running = True”。 而不是將while循環設為“ while True:”,而應使其變為“ while running = True:”。 最后,在while循環中,如果您按ESC鍵,請設置“ running = False”
這是pygame的示例:
import pygame
pygame.init()
def record():
# init
running = True
while running == True:
# record
events = pygame.event.get()
for event in events:
if event.type == pygame.K_ESCAPE:
running = False
quit()
record()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.