Guide to Python's keyboard Module

Introduction

Python is one of the most suitable languages for automating tasks. Whether it's repeatable (ethical) web scraping after some time period, starting some programs on a computer start up, or automating sending mundane e-mails, Python has a lot of modules that make your life easier.

One of these is a module called keyboard, and it takes full control of your keyboard. With this module, you can type out anything, create hot-keys, create abbreviations, block the keyboard, wait for input, etc.

In this guide, we'll take a look at how to set up and use the keyboard module in Python.

Note: Applications working with automating human-like processes should be developed ethically and responsibly. The keyboard module is made to be very observable, and thus makes it both discouraged and transparent if anyone's using it to create key-loggers or malicious bots.

Installing the keyboard Module

Note: The version of Python used in this guide is 3.8. However, the keyboard module can work with both Python 2.x and Python 3.x.

If you're using Linux, in order to use this library, you must install it as root. If you don't, you'll get an:

ImportError: You must be root to use this library on linux.

Also, when running your script, you should run it with root privileges:

$ sudo pip3 install keyboard
$ sudo python3 my_script.py

On Windows and MacOS, as the privileges work much differently - you can install it simply via pip and run the scripts:

$ pip install keyboard
$ python my_script.py

Note: For MacOS, you might have to allow the Terminal or other apps to change the state of your machine, such as by typing. Also keep in mind that as of September 2021, the library is still experimental on MacOS.

The keyboard Module's Functions

There are a lot of functions in this module that can be used to simulate keyboard actions.

  • keyboard.write(message, [delay]) - writes a message, with or without a delay.
  • keyboard.wait(key) - blocks the program until the key is pressed. The key is passed as a string ('space', 'esc', etc.)
  • keyboard.press(key) - presses a key and holds until the release(key) function is called.
  • keyboard.release(key) - releases a key.
  • keyboard.send(key) - presses and releases a key.
  • keyboard.add_hotkey(hotkey, function) - creates a hotkey which when pressed, executes a function.
  • keyboard.record(key) - records keyboard activity until key is pressed.
  • keyboard.play(recorded_events, [speed_factor]) - replays events recorded with keyboard.record(key) function, with an optional speed_factor.

We'll go through all of these, though, here's a quick example:

>>> import keyboard
>>> keyboard.write("Hello")
>>> Hello

The Hello message appears on the screen, in the terminal, as if you've written it. You can automate a command very easily, and create a hotkey alias for it. Here's a (crude) example of exiting the Python REPL, writing a curl command and executing it:

>>> import keyboard
>>> keyboard.write("exit()"); keyboard.send("enter"); keyboard.write("curl https://www.google.com"); keyboard.send("enter");
>>> exit()
curl https://www.google.com
$ curl https://www.google.com
<!doctype html><html itemscope=""...

keyboard's write() and wait() Functions

The write() command writes a message, as we've seen before, with an optional delay in the start. If no delay is set, writing is instant. It's very nicely combined with the wait() function, which awaits a certain key to be pressed.

For instance, we can create a make-shift macro, tied to, say 1, which responds to that input with a new message. Note that there's an actual way to create hotkeys instead of this, which we'll cover later.

We'll create an infinite True loop to check for the key being pressed, and you can run the script in the background:

import keyboard

while True:
    keyboard.wait("1")
    keyboard.write("\n The key '1' was pressed!")

Note: Special characters are not supported by this function, so if you add, say, ! - you'll get hit with a StopIteration exception.

keyboard's press(), release() Functions

Since it's hard to simulate press() and release() so that the actions are visible, we'll also see record() and play() in action.

The press() function presses a key and releases it when you call release() on the same key. Note that you can't sleep() for some time to simulate holding down a key:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

>>> import keyboard
>>> from time import sleep
>>> keyboard.press("a")
>>> sleep(1)
>>> keyboard.release("a")
>>> a

However, you can hold down some special keys, such as [SHIFT] or [CTRL] this way:

>>> keyboard.press("shift")
>>> keyboard.write("lowercase")
>>> keyboard.release("shift")

>>> LOWERCASE

keyboard's record() and play() Functions

It's not always about inputting new keys in - sometimes, you'd like to record what's going on and play it back. Keep in mind that you'll need administrator privileges to record any input like this, as the technology can easily be used to create keyloggers.

The record() function accepts a trigger key, until which it records, and returns a sequence of events of type KeyboardEvent. You can then chuck this sequence of events into the play() function, which faithfully replays them, with an optional speed_factor argument that acts as a multiplier for the speed of the original events:

import keyboard
recorded_events = keyboard.record("esc")
keyboard.play(recorded_events)

If we're to print the recorded_events, they'd look something like:

KeyboardEvent(w up), KeyboardEvent(o down), ...]

The effects of these methods are best seen as a GIF or recreated on your machine. For instance, a sequence of writing a message, deleting it and writing a different one instead:

keyboard's send() function

The send() function encompasses press() and release() together, and is used for single keys, unlike write() which is used for entire sentences:

import keyboard

recorded_events = keyboard.record("s")

keyboard.send("w")
keyboard.send("a")

keyboard.play(recorded_events)

Once s is pressed, the w and a keys are replayed.

The press() function can also accept combinations of pressed keys. You can send a combination of "ctrl+shift+s" for instance and the dialogue for saving a file should pop up, if you're in an application that supports that operation:

import keyboard

while True:
    keyboard.wait("s")
    keyboard.press("ctrl+shift+s")
    # Or for MacOS
    keyboard.press("command+shift+s)

Though, this isn't the right way to add hotkeys. Rather, you can use the add_hotkey() function.

keyboard's add_abbreviation() Function

The add_abbreviation() function is a pretty nifty one, as it allows you to define abbreviations for long inputs, and replaces the abbreviated versions with the saved full versions.

For instance, similar to how services like Google save your email for most input forms, you can create your own abbreviation and trigger it via [SPACE]:

>>> import keyboard
>>> keyboard.add_abbreviation("@", "[email protected]")

While running, if you type @ followed by a [SPACE] - the long-form input will replace the typed @.

keyboard's add_hotkey() Function

The add_hotkey() function accepts a hotkey you'd like to save, or a combination of keys, and a function. It's easy to pass in anonymous lambda functions here, though you can also add named functions.

For instance, let's add a hotkey for CTRL+j, which triggers a lambda function that logs this:

import keyboard

keyboard.add_hotkey("ctrl+alt+j", lambda: print("ctrl+alt+j was pressed"))

The hotkey, ctrl+alt+p, is saved and when you press this combination, you should see the output of the lambda.

Conclusion

The keyboard module is a lightweight and simple library used for simulating keystrokes and simple automation in Python. It's not very feature-rich, but can be used to automate some of the tasks you might be performing in your day-to-day work, or simply for a bit of fun.

A more mature, powerful module that can be used as an alternative is pynput.

Last Updated: October 24th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupEditor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms