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 dec 2020 · General Python Tutorials


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

Related: How to Send Emails in Python.

We will be using 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 "[email protected]":

# replaces every "@email" followed by a space with an actual email
keyboard.add_abbreviation("@email", "[email protected]")

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

Second, you can also invoke a callback everytime 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 in 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 comes into play:

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

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

But now what if you want to write a long text and not just specific buttons ? send() would be inefficient. Luckily for us, 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 delay to 0.1 indicates 0.1 seconds to wait between keypresses, 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 'esc' button, and then we play these events again using play() method.

You can explore what events list contain 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 in 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!

Dive Deeper with Python

Finally, many of the Python concepts aren't discussed in detail here, if you feel you want to dig more to Python, I highly suggest you get one of these amazing courses:

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

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

Learn Also: How to Convert Python Files into Executables.

Happy Coding ♥

View Full Code
Sharing is caring!



Read Also




Comment panel