Reputation: 23
I am tying to make a program in which I press certain hot key which will then detect a key press and tell which key I pressed but whenever I press the hotkey, program doesn't respond to any keypress even the escape key and keeps running.
import keyboard
def dostuff():
print("Mew")
key = keyboard.read_key()
print('I have detected', type(key))
keyboard.add_hotkey('a', lambda: dostuff())
keyboard.wait('esc')
Can anyone tell what's the issue?
Upvotes: 0
Views: 556
Reputation: 106
If you dont want to use the keyboard module, you can use pynput, which does the same thing,
install pynput using pip
pip install pynput
here is the code:-
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener when esc key is pressed
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Upvotes: 1