# Function to execute when a key is pressed, using try and except because of special keys (function keys) defkeyboard_on_press(key): global isEnd try: print(f'Letter key {key.char} pressed') except AttributeError: print(f'Special key {key}') if key == keyboard.Key.esc: isEnd = True returnFalse
# Interrupted program deffunction(): # Infinite loop of the main program whileTrue: pass
# Create main program thread t = threading.Thread(target=function) t.daemon = 1 # Start keyboard listening thread listener.start() # Start main program thread t.start() whileTrue: if isEnd: return
if __name__ == "__main__": main()
Executing the program when a key is pressed
Detecting the ESC key
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import keyboard
# Program to execute when a key is pressed deffunction(): pass