Keyboard module: Controlling your Keyboard in Python

Learn how to use keyboard module in Python to take full control of your keyboard such as hooking global events, registering hotkeys, simulating key presses and releases and much more.
  · 5 min read · Updated jun 2022 · General Python Tutorials

Kickstart your coding journey with our Python Code Assistant. An AI-powered assistant that's always ready to help. Don't miss out!

Disclosure: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.

In this tutorial, you will learn how to use the keyboard module to control your computer keyboard in Python, this is of course useful for many tasks such as enabling us to automate various routine desktop tasks, building reinforcement learning agents, and much more.

Table of content:

Related: How to Send Emails in Python.

We will be using the keyboard module, let's install it:

pip3 install keyboard

Alright, open up a Python interactive shell or a Jupyter notebook/lab and follow along.

First, let's import the module:

import keyboard

Adding Hotkeys & Abbreviations

This module provides us with the function add_abbreviation() that enables us to register a hotkey that replaces one typed text with another. For instance, let's replace the text "@email" to the email address "test@example.com":

# replaces every "@email" followed by a space with an actual email
keyboard.add_abbreviation("@email", "test@example.com")

Now execute this line of code, and then open up any text editor and write "@email" followed by a space, you'll see the magic!

Second, you can also invoke a callback every time a hotkey is pressed:

keyboard.add_hotkey("ctrl+alt+p", lambda: print("CTRL+ALT+P Pressed!"))

"ctrl+alt+p" refers to the button CTRL, ALT, and P character pressed at once, so whenever these buttons are pressed at once, the callback will get called, in this case, it will just print a simple message, but you can make anything you want, such as desktop shortcuts.

Checking Whether a Button is Pressed

You can also check whether a button is actually pressed:

# check if a ctrl is pressed
print(keyboard.is_pressed('ctrl'))

Pressing & Releasing Buttons

Next, you can also simulate key presses using the send() function:

# press space
keyboard.send("space")

This will press and release the space button. In fact, there is an equivalent function press_and_release() that does the same thing.

You can also pass multi-keys:

# multi-key, windows+d as example shows the desktop in Windows machines
keyboard.send("windows+d")

The + operator means we press both buttons at the same time, you can also use multi-step hotkeys:

# send ALT+F4 in the same time, and then send space, 
# (be carful, this will close any current open window)
keyboard.send("alt+F4, space")

But what if you want to press a specific key but you don't want to release it? Well, press() and release() functions come into play:

# press CTRL button
keyboard.press("ctrl")
# release the CTRL button
keyboard.release("ctrl")

So this will press the CTRL button and then release it, you can do anything in between, such as sleeping for a few seconds, etc.

Another alternative is the send() function itself; it has two parameters, do_press and do_release which both default to True. If you only want to press the key with send(), you can simply use keyboard.send("ctrl", do_release=False) to not release the key.

Writing Text

But now what if you want to write a long text and not just specific buttons? send() would be inefficient. Luckily for us, the write() function does exactly that, it sends artificial keyboard events to the OS simulating the typing of a given text, let's try it out:

keyboard.write("Python Programming is always fun!", delay=0.1)

Setting the delay to 0.1 indicates 0.1 seconds to wait between key presses, this will look fancy like in hacking movies!

Recording & Playing Keyboard Events

You can do many more cool things with this module such as recording keyboard events using record() function and playing them again using play() function:

# record all keyboard clicks until esc is clicked
events = keyboard.record('esc')
# play these events
keyboard.play(events)

I passed 'esc' to record() method to record key presses and releases until I press the 'esc' button, and then we play these events again using the play() method.

You can explore what the events list contains by simply printing it, or you may use get_typed_strings() to get typed strings:

# print all typed strings in the events
print(list(keyboard.get_typed_strings(events)))

Here is what I typed:

['Python is indeed the best programming language.!', 'right?', '', '']

Another interesting function is on_release() function which accepts a callback that is executed whenever a key is released:

# log all pressed keys
keyboard.on_release(lambda e: print(e.name))

This will print anything you press on your keyboard, for more information about how to use this function to build a keylogger for educational purposes, check this tutorial.

Finally, if you want to remove all keyboard hooks in use, including hotkeys, abbreviations, etc:

keyboard.unhook_all()

Conclusion

I just introduced the module to you, please check the documentation or just type help(keyboard) in a Python interactive shell for learning other functionalities and methods.

You can also take full control of your mouse, the same author of this module made another one for handling the mouse!

With such modules, you can build desktop automation scripts, keyboard shortcuts, keyloggers (although the author isn't responsible), and much more!

Feel free to visit this site if you want to get instant Python assignment help from experts. A team of Python programmers will do your Python homework with excellence.

Dive Deeper with Python

Finally, if you're a beginner and want to learn Python, I suggest you take the Python For Everybody Coursera course, in which you'll learn a lot about Python, good luck!

Alright, that's it, check the full code here.

Learn Also: How to Convert Python Files into Executables.

Happy Coding ♥

Loved the article? You'll love our Code Converter even more! It's your secret weapon for effortless coding. Give it a whirl!

View Full Code Understand My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!