Detecting keystrokes in Python
If you need to access hardware like input devices like keyboards, there are modules in Python that can make your life much easier. Using such modules, you can easily perform the tasks you want without having to deal with the complexity of the system.
In this article, you will learn how to use modules in Python to detect key presses. There are many modules for detecting key presses in Python, two of the most popular and widely used modules are keyboard
and pynput
.
keyboard
Detect keystrokes
in Python using the module in Python
keyboard
The module allows us to have full control over the keyboard and comes with various predefined methods for us to choose from. These methods make it easier for us to use the keyboard and detect the physical keys pressed by the user on the keyboard.
To install keyboard
the module, execute the following command in your command prompt or terminal.
pip3 install keyboard
First, you have to keyboard
import the module into your program. Here, we use three methods in Python to detect key presses, namely 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
read_key()
will read the key the user pressed on the keyboard, and if it's the key you want, in this case p
, it will print out You pressed p
the information of . read_key()
The function returns a character.
is_pressed()
The function receives a character as input and returns if it matches the key pressed by the user, True
otherwise returns False
.
on_press_key()
It takes two parameters as input, the first is a character, the second is a function. If the user presses on_press_key()
a key that matches the key specified by the first parameter of the function, it will only execute the function you passed in as the second parameter.
pynput
Detect keystrokes
in Python using the module in Python
pynput
The 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 to detect keys on the keyboard. Before using this module, you must first install it using the following command.
pip3 install pynput
To use this module to detect key presses, you first have to pynput
import it from the module keyboard
.
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 output above may vary depending on the keys pressed by the user.
To detect key presses, we define two functions, on_press
and on_release
. When the user presses a key on the keyboard, function on_press
will be executed, and when the user releases the key, on_release
function will be executed.
Both functions simply print the keys pressed and released by the user to the console window. You can change the implementation of these two functions to suit your needs.
Then at the end, we have a listener that will listen for keyboard events and execute the on_press
and on_release
functions accordingly.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Writing logs to a file in Python
Publish Date:2025/05/06 Views:132 Category:Python
-
This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file
Comparing two dates in Python
Publish Date:2025/05/06 Views:97 Category:Python
-
This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin
Reload or unimport modules in Python
Publish Date:2025/05/06 Views:58 Category:Python
-
Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu
Pausing program execution in Python
Publish Date:2025/05/06 Views:156 Category:Python
-
This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo
Importing modules from a subdirectory in Python
Publish Date:2025/05/06 Views:190 Category:Python
-
This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files
Sleeping for a number of milliseconds in Python
Publish Date:2025/05/06 Views:124 Category:Python
-
In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab
Python Numpy.pad Function
Publish Date:2025/05/06 Views:104 Category:Python
-
In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd
Generating Random Colors in Python
Publish Date:2025/05/06 Views:135 Category:Python
-
In the digital world, colors are represented in different formats. RGB, Hexadecimal format are just some of the commonly used formats. In this tutorial, we will learn how to generate random colors in Python. When we talk about generating ra
Getting the name of a class in Python
Publish Date:2025/05/06 Views:83 Category:Python
-
Just like object constructors, classes can be defined as user-defined prototypes for creating objects. class Classes can be created using the keyword . A class is a data structure that can contain both data members and member methods. This