3

I have a program that is an endless loop that prints "program running" every 5 seconds and I want to stop it when I press the end key.

So I created a key listener that returns false if the end key is pressed. That should work if I won't have the endless loop. And I want it to work even when I'm in the endless loop.

Here's my code:

from pynput import keyboard
import time
def on_press(key):
    print key
    if key == keyboard.Key.end:
        print 'end pressed'
        return False        
with keyboard.Listener(on_press=on_press) as listener:
    while True:
        print 'program running'
        time.sleep(5)
    listener.join()
Doron Sever
  • 65
  • 2
  • 2
  • 9

1 Answers1

9
from pynput import keyboard
import time

break_program = False
def on_press(key):
    global break_program
    print (key)
    if key == keyboard.Key.end:
        print ('end pressed')
        break_program = True
        return False

with keyboard.Listener(on_press=on_press) as listener:
    while break_program == False:
        print ('program running')
        time.sleep(5)
    listener.join()
Dariusz Krynicki
  • 2,544
  • 1
  • 22
  • 47