Detect keypress in Python

Detect keypress in Python

Python allows us to work with user input in its programs. We can also work with hardware devices in Python.

In this article, we will discuss how to detect keypress in Python.

Using the keyboard module to detect keypress in Python

The keyboard module is well equipped with different functions to perform operations related to keyboard input, detecting-simulating key presses, and more. This module works normally on Windows but requires the device to be rooted on Linux devices. To detect keypress, we can use a few functions from this module.

The read_key() function from this module is used to read the key pressed by the user. We can check whether the pressed key matches our specified key.

See the following example.


A Key Pressed

If you get output as below:

ModuleNotFoundError: No module named ‘keyboard’

You need to install keyboard module first.
You can use following command to install keyboard module.

pip install keyboard

The wait() function waits for the user to press some specific key and then resume the program execution.

For example,


A Key Pressed

We can also use the is_pressed() function to check whether a specific key is pressed or not. It will return a True or False value.

For example,


A Key Pressed

The on_press_key() function can execute a function when a specific key is pressed. We have to pass the function and the required key as parameters to this function.

We will use this function in the following code.


A Key Pressed

Using the pynput module to detect keypress in Python

The pynput module allows us to work with different input devices like keyboard and mouse.

We will create two functions that will be collected using the Listener function of this module.

See the following code.



There are a lot of things happening in the above example.

  • The press() function will be executed when we press the key and print the key.
  • Similarly, the on_release() function will be executed when the key is released.
  • These two functions are collected in the Listener() function using the on_press and on_release parameters.
  • We can also stop the Listener() function by pressing some specific key. In our example, if the spacebar is pressed, the release function will return False and the Listener() function will stop.

Using the msvcrt module to detect keypress in Python

The msvcrt is another Windows-only module that can detect keypresses.

We will detect a keypress and print that key using the following code.

Key Pressed b’r’

In the above example,

  • The kbhit() function waits for a key to be pressed and returns True when it is pressed.
  • The getch() function returns the key pressed in a byte string. Notice the b in the output.
  • The break statement will come out of this code block. If it is removed, then the code will keep on executing.
    That’s all about how to detect keypress in Python.


You may also like:

Related Posts

  • Convert dict to String in Python
    17 December

    Convert dict to string in python

    Table of ContentsHow to convert dict to string in python?Using str() method.Using the pickle module.Using the for loop.Using the json.dumps() method. In this post, we will see how to convert dict to String in Python. Python contains several data structures, and more often than not, there is a need for the conversion of one type […]

  • Python range float
    17 December

    Generate float range in Python [9 ways]

    Table of ContentsWhat is a floating-point number in Python?Why not use the simple and popular range() function?Python range float : How to generate floating-point numbers in Python?Using the numpy.linspace() method.Using the numpy.arange() method.Using list comprehension.Using generator comprehension.Using yield generator.Using a user-defined function.Using the itertools module and its functions.Using the map() function along with a lambda […]

  • Python callback function
    13 December

    Callback function in Python

    Table of ContentsWhat is Callback Function in Python?Applications of Callback Functions in PythonConclusion In python, functions are first-class objects. In other words, we can pass a function to a different function as an input argument. We can return a function from another function, and we can assign a function to a variable. In this article, […]

  • ValueError: too many values to unpack
    10 December

    [Fixed] ValueError: too many values to unpack (expected 2)

    Table of ContentsWhat is unpacking in python?What is ValueError: too many values to unpack (expected 2)?How to resolve ValueError: too many values to unpack (expected 2)?Conclusion While programming in python, we can assign values to two or more variables in a single statement. While doing so, you might get the ValueError exception with the message […]

  • Python List of dictionaries
    09 December

    List of Dictionaries in Python

    Table of ContentsHow to Create a List of Dictionaries in Python?How to Access Elements of a List of Dictionaries?Search in a List of Dictionaries in PythonUpdate Values in a List of Dictionaries in PythonHow to Sort List of Dictionaries in Python?Conclusion We use both lists and dictionaries in our python programs. Lists are used to […]

  • Python if not
    08 December

    Python If with NOT Operator

    Table of ContentsNOT Operator and IF Statement in PythonApplications of the if statement with not operator in pythonConclusion In python, we use conditional statements to implement logic in our program. For this, we use boolean expressions with if statements. In this article, we will see how we can use the if statement with the not […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.