2

How do I break this loop with a keystroke such as Esc ? This example captures the keystroke but never passes the variable into the while loop.

from pynput import keyboard
count = 0
stop = 0
while True: 
    def press_callback(key):
        if key == keyboard.Key.esc:
            def stop_loop():
                stop = 1
                return stop
            print('You pressed "escape"! You must want to quit really badly...')
            stop = stop_loop()
        return stop 

    count +=1
    print (count)
    if stop == 1:
        break
    if count == 1:
        l = keyboard.Listener(on_press=press_callback)
        l.start()

I'm using Ubuntu 18.04.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
SDM1212
  • 153
  • 12

2 Answers2

1

Update your stop_loop method like this:

def stop_loop():
  global stop
  stop = 1
  return stop

If you don't declare global stop then instead of updating stop variable you defined at the beginning of the file you'll create a new local stop variable inside stop_loop method.

Probably read this for better understanding: https://realpython.com/python-scope-legb-rule/

GProst
  • 9,229
  • 3
  • 25
  • 47
0

Here is the final working solution:

from pynput import keyboard
count = 0
stop = 0

def press_callback(key):

    if key == keyboard.Key.esc:
        def stop_loop():
            global stop
            stop = 1
            return stop
        print('Get Out')
        stop = stop_loop()
     

    return stop
    
l = keyboard.Listener(on_press=press_callback)
l.start()

while True:
    count += 1
    print (count)
    if stop == 1:
        break    

SDM1212
  • 153
  • 12
  • I found a work around by using cv2.namedWindow("window", WINDOW_NORMAL) and moving the open window mannualy. – SDM1212 Sep 25 '20 at 12:41