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


from pynput import keyboard

def on_press(key):
        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_release=on_release) as listener:

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


import keyboard

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


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

Categorized in:

Tagged in: