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.

Output:

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,

Output:

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,

Output:

True
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.

Output:

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.

Output:

‘a’
‘b’
Key.space

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.

Related Posts

  • Convert String to Boolean in Python
    20 June

    Convert String to Boolean in Python

    Table of ContentsUsing the bool() method to convert string to Boolean in Python.Using the distutils.util.strtobool() method to convert a string to Boolean in Python.Using list comprehension to convert a string to Boolean in Python.Using the map() function along with Lambda function to convert a string to Boolean in Python.Using the JSON parser to convert a […]

  • Convert float to int in Python
    19 June

    Convert float to int in Python

    Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

  • Convert unix timestamp to datetime in Python
    21 May

    Convert Unix timestamp to DateTime in python

    Table of ContentsUsing fromtimestamp() FunctionUsing strftime() FunctionUsing to_datetime() Function A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC. In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python. Using fromtimestamp() […]

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.