【问题标题】:Stop a while loop by escape key?通过转义键停止while循环?
【发布时间】:2018-07-23 18:38:43
【问题描述】:

我编辑了我的问题,因为现在当我在 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()

【问题讨论】:

  • 为什么不使用 Ctrl+C? (这会引发KeyboardInterrupt
  • 你能演示一下吗?
  • 我试图使用转义键来终止录制,但它根本不会终止循环
  • 当一个程序正在运行并且用户按下 Ctrl+C 时,KeyboardInterrupt 就会被触发。在 Python IDE 中试试这个:while True: print(1)。按回车,等待几秒钟,然后按 Ctrl+C 看看会发生什么。

标签: python cv2


【解决方案1】:

不幸的是,除非您希望循环的每次迭代都有一个按键,否则很难监听按键,这对于您正在做的事情是不切实际的。我认为 Joel 在 cmets 中是正确的,您应该使用

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 资源。

因为你使用 PyCharm 作为你的 IDE,Ctrl+C 可能不适合你 - 试试 Ctrl+F2 代替。

【讨论】:

  • 我尝试使用上述解决方案,但按 ctrl+c 后循环没有终止
  • 我已经为你更新了我的答案,因为你使用 PyCharm,使用 ctrl+f2
  • 我只是使用了 ctrl+f2 键,但循环仍然没有终止
  • 无法找出原因
  • 如果我在 out.write(frame) 之前使用 cv2.imshow('Screen', frame) 然后运行我的程序,我可以通过按转义停止录制键
【解决方案2】:

您应该创建一个名为 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()

【讨论】:

  • 到底是什么? pygame 来自哪里?这不是一个好的解决方案。
  • 它没有帮助
  • 我尝试了答案,但尽管按下了退出键,循环仍然运行
猜你喜欢
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多