Detect Keypress in Python

  1. Detect KeyPress Using the keyboard Module in Python
  2. Detect KeyPress Using the pynput Module in Python

If you need access to the hardware like input devices such as the keyboard, there are modules available in Python which can make your lives much easier. Using such modules, you can easily perform the task you want without dealing with the complexities of the system.

In this article, you will learn how to detect keypress using modules in Python. There are many modules used to detect keypress in Python, and out of which, the two most popular and widely used modules are keyboard and pynput.

Detect KeyPress Using the keyboard Module in Python

The keyboard module allows us to take full control of the keyboard and comes with various predefined methods to choose from. These methods make it much easier for us to work with the keyboard and detect the user’s physical keypresses on the keyboard.

To install the keyboard module, execute the below command inside your command prompt or terminal.

pip3 install keyboard

First, you have to import the keyboard module into the program. Here, we are using three methods to detect keypress in Python read_key(), is_pressed() and on_press_key().

import keyboard

while True:
    if keyboard.read_key() == "p":
        print("You pressed p")
        break

while True:
    if keyboard.is_pressed("q"):
        print("You pressed q")
        break
        
keyboard.on_press_key("r", lambda _:print("You pressed r"))

Output:

You pressed p
You pressed q
You pressed r

The read_key() will read which key a user has pressed on the keyboard, and if it’s that key which you wanted, in this case, p, it will print the message You pressed p. The read_key() function returns a character.

The is_pressed() takes a character as an input, and if it matches with the key which the user has pressed, it will return True and False otherwise.

The on_press_key() takes two parameters as an input, the first is the character, and the second is the function. If the user presses the key that matches the key specified as the first parameter of the on_press_key() function, it will only execute the function you have passed in as the second parameter.

Detect KeyPress Using the pynput Module in Python

The pynput module is used to detect and control input devices, mainly mouse and keyboard. But in this tutorial, you will only see how to use this module for detecting keypress on the keyboard. Before using this module, you first have to install it using the command below.

pip3 install pynput

To use this module for detecting keypress, you first have to import Keyboard from pynput module.

from pynput import keyboard

def on_press(key):
    try:
        print('Alphanumeric key pressed: {0} '.format(
            key.char))
    except AttributeError:
        print('special key pressed: {0}'.format(
            key))

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

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

Output:

Alphanumeric key pressed: a 
Key released: 'a' 
Alphanumeric key pressed: b
Key released: 'b'
special key pressed: Key.ctrl_l 
Key released: Key.ctrl_l

Note that the above output may vary depending upon which keys are pressed by the user.

To detect keypress, we are defining two functions, on_press and on_release. The function on_press will be executed when the user will press a button on the keyboard, and as soon as the user releases that button, the on_release function will be executed.

Both functions are only printing the keys pressed and released by the user to the console window. You can change the implementation of these two functions based on your requirements.

Then at the end, we have a Listener that will listen to the keyboard events, and it will execute the on_press and on_release functions accordingly.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Input

  • Check if Input Is Integer in Python