How can I track down the keyboard button if the python script is running in the background?
|
2 answers
You can track button presses through the keyboard module.
This is an example for tracking hotkey clicks:
def foo(): print('World') # pip install keyboard import keyboard keyboard.add_hotkey('Ctrl + 1', lambda: print('Hello')) keyboard.add_hotkey('Ctrl + 2', foo) keyboard.wait('Ctrl + Q')Tracking all button clicks:
# pip install keyboard import keyboard def print_pressed_keys(e): print(e, e.event_type, e.name) keyboard.hook(print_pressed_keys) keyboard.wait()
|
Installation:
pip install pynput In this way:
from pynput.keyboard import Key, Listener def on_press(key): print('{0} pressed'.format(key)) def on_release(key): print('{0} release'.format(key)) if key == Key.esc: # Stop listener return False # Collect events until released with Listener(on_press=on_press, on_release=on_release) as listener: listener.join() |