python listen for keyboard input code example
Example 1: python check key press
import keyboard
# if key 'a' is pressed
if keyboard.is_pressed('a'):
print('a key has ben pressed')
Example 2: python listen to keyboard input
# For windows
from pynput import keyboard
def on_press(key):
try:
k = key.char # single-char keys
except:
k = key.name # other keys
print('Key pressed: ' + k)
return False # stop listener; remove this if want more keys
listener = keyboard.Listener(on_press=on_press)
listener.start() # start to listen on a separate thread
listener.join() # remove if main thread is polling self.keys