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.
Table of Contents [hide]
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:
If you get output as below:
You need to install keyboard module first.
You can use following command to install keyboard module.
The wait()
function waits for the user to press some specific key and then resume the program execution.
For example,
Output:
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:
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:
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:
‘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 theon_press
andon_release
parameters. - We can also stop the
Listener()
function by pressing some specific key. In our example, if the spacebar is pressed, therelease
function will return False and theListener()
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.
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 theb
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.