Skip to content

Python keyboard press detect | Example code

  • by

How to detect key presses?

Using pynput and keyboard module can detect keyboard press in Python. You have to use an event Listener.

Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

OR

Use IDE

Python module keyboard

Example detect keyboard press in Python

Simple example code will print whichever key you are pressing plus start the action as you release the ‘ESC’ key.

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()

Output:

Python keyboard press detect

Find specific keypress

Print message if “q” key has pressed.

import keyboard

while True:  # making a loop
    try:
        if keyboard.is_pressed('q'):  # if key 'q' is pressed
            print(' You Pressed A Key!')
            break
    except:
        break

Output: q You Pressed A Key!

Do comment if you have any doubts or suggestions on this python keyboard topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading