Python doesn’t support key press detection by default in its standard library. However, we can use some of the third-party libraries such as pynput and keyboard to do that.

Using pynput Library

Using the Pynput library we can control and monitor the input devices and also listen to the keyboard events.

Install the pynput using pip:

pip install pynput

Example:

from pynput import keyboard

def on_press(key):
    try:
        print(f'Alphanumeric key pressed: {key.char}')
    except AttributeError:
        print(f'Special key pressed: {key}')

def on_release(key):
    print(f'Key released: {key}')
    if key == keyboard.Key.esc:
        # Stop the listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

The above script will register the on_press & on_release listeners which will print the keys pressed. The listener will be stopped by pressing the ESC key button.

Using keyboard Library

We can also use the keyboard library to listen to the keyboard events. We don’t need a graphical interface for this library.

Install the keyboard library

pip install keyboard

Example:

import keyboard

def on_key_event(event):
    print(f'Key {event.name} pressed')

keyboard.hook(on_key_event)
keyboard.wait('esc')

The above example prints the name of the key pressed until the escape key is pressed.

Categorized in:

Tagged in: