pythonpython-3.xwhile-looppython-keyboard

How to stop a function & exit program running in a while loop on key press?


I need to stop a program when a keyboard key q is pressed. How can I achieve that in the below code? How can I ignore time.sleep & detect a keypress & exit the program by printing something? Currently, the keypress gets detected only after 10 seconds. Suppose I am pressing q after 3 seconds the program doesn't exit.

import sys
import time

import keyboard

def hd():
    print("Hi")
    time.sleep(10)
    if keyboard.is_pressed("q"):
        print(keyboard.is_pressed("q"))
        sys.exit()


while True:
    hd()

Solution

  • Instead of polling the keyboard to check if a certain key is pressed, you can just add a hotkey. When the hotkey q (or whatever key you like) is pressed, a trigger function quit is called.

    import keyboard
    import time
    import sys
    
    exitProgram = False
    
    # prepare to exit the program
    def quit():
        global exitProgram
        exitProgram=True
        
    # set hotkey    
    keyboard.add_hotkey('q', lambda: quit())
    
    # main loop to do things
    while not exitProgram:
        print("Hello")
        time.sleep(1)
        
    print("bye bye")
    sys.exit()