Search code examples
pythonpython-2.7pynput

How to stop a program when a key is pressed in python?


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

Solution

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