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:
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
# replaces every "@email" followed by a space with an actual email keyboard.add_abbreviation("@email", "email@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.
You can also check whether a button is actually pressed:
# check if a ctrl is pressed print(keyboard.is_pressed('ctrl'))
Next, you can also simulate key presses using the
# 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")
+ 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,
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_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.
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!
You can do many more cool things with this module such as recording keyboard events using
record() function and playing them again using
# record all keyboard clicks until esc is clicked events = keyboard.record('esc') # play these events keyboard.play(events)
record() method to record key presses and releases until I press the
'esc' button, and then we play these events again using the
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))
Finally, if you want to remove all keyboard hooks in use, including hotkeys, abbreviations, etc:
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.
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 ♥View Full Code