pynput
has special class Listener
to catch pressed keys. It runs in thread and it doesn' need while True
so it doesn't block main code.
Press ESC
to stop it.
from pynput.keyboard import Key, Controller, Listener
def on_press(key):
print('{} pressed'.format(key))
#print(dir(key))
try:
if key.char == 'u':
keyboard.press('w')
keyboard.release('w')
except Exception as ex:
print(ex)
def on_release(key):
print('{} release'.format(key))
if key == Key.esc:
# Stop listener
return False
# --- main ---
keyboard = Controller()
listener = Listener(on_press=on_press, on_release=on_release)
listener.start()
# ... other code ...
listener.join()
BTW:
If you want global macros/hotkeys in system and use Linux then you could use special program AutoKey for this. It is created with Python and it is has GUI to create macros/script/etc.
If you want global macros/hotkeys in system and use Windows you could rather use popular AutoHotKey
If you want to create macros/hotkeys in some GUI
programs then you should use GUI
functions for this.