1import keyboard # using module keyboard
2while True: # making a loop
3 try: # used try so that if user pressed other than the given key error will not be shown
4 if keyboard.is_pressed('q'): # if key 'q' is pressed
5 print('You Pressed A Key!')
6 break # finishing the loop
7 except:
8 break # if user pressed a key other than the given key the loop will break
1# pip3 install pynput
2
3from pynput.keyboard import Key, Listener
4
5
6def show(key):
7
8 pressed_key = str(key).replace("'", "")
9 print(" key: ", pressed_key)
10
11 if key == Key.esc:
12 # Stop listener
13 return False
14
15
16# Listener
17with Listener(on_press=show) as listener:
18 listener.join()
19