1

I edited my question because now when i ran my code outside Pycharm (IN Powershell) the keyboard interrupt works fine but now i am struggling to terminate the code on Escape key press.

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()
9
  • Why not use Ctrl+C? (this would raise a KeyboardInterrupt) Commented Jul 23, 2018 at 18:40
  • can you demontstate how ? Commented Jul 23, 2018 at 18:41
  • i was trying to use escape key to terminate the recording but it simply won't terminate the loop Commented Jul 23, 2018 at 18:42
  • Whenever a program is running and the user presses Ctrl+C, a KeyboardInterrupt is raised. Try this in a Python IDE: while True: print(1). Press enter, wait a few seconds, then press Ctrl+C and see what happens. Commented Jul 23, 2018 at 18:42
  • 2
    stackoverflow.com/questions/39796689/… Commented Jul 23, 2018 at 18:48

2 Answers 2

0

Unfortunately it's pretty difficult to listen for keypresses unless you expect one for every iteration of your loop, which for what you're doing is impractical. I think Joel has it right in the comments, you should be using

Ctrl+C

and catching the KeyboardInterrupt like this

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

This way, the KeyboardInterrupt won't terminate the program, it'll just end the while loop, allowing you to release your writer and cleanup the rest of the cv2 resources.

Because you're using PyCharm as your IDE, Ctrl+C might not work for you - try Ctrl+F2 instead.

Sign up to request clarification or add additional context in comments.

7 Comments

i tried using the above solution but the loop didn't terminate after i pressed ctrl+c
I've updated my answer for you because you use PyCharm, use ctrl+f2
i just used ctrl+f2 key but the loop still didn't terminate
Can't figure out the reason for this
and here is another problem if i use cv2.imshow('Screen', frame) just before out.write(frame) and then run my program i am able to stop the recording by pressing the escape key
|
0

You should make a variable called running! Set 'running = True' before the while loop. And instead of the while loop being 'while True:', make it 'while running = True:'. Finally, in the while loop, if you hit ESC, set 'running = False'

Here is an example with 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()

3 Comments

What on Earth? Where has pygame come from? This is not a good solution.
and it didn't helped
i tried the answer but the loop still ran despite pressing escape key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.