/ tuesdaytooling

Tuesday Tooling: Record / Replay Keystrokes With Python

For this weeks Tuesday Tooling we take a look at a Python library that offers to simulate and record keyboard input!

So what is it called?

Keyboard : Record and simulate keyboard events on Windows and Linux.

Where can I find it?

You can find it on pypi

Who made it?


What uses does it have?

  • In development environments a user could assign a long key combination / sequence that could be executed by pressing a certain combination (eg CTRL+ALT+P could open a new Python file in IDLE and open the save dialog ready)
  • For Raspberry Pi users, this could be a simpler way to create keyboard events that control devices such as robots and homemade game controllers. Right now to capture keyboard input for a Pi robot we need to use PyGame (Which is awesome BTW) but a little tricky to get working. We could possibly use this library to make it easier for new coders to build keyboard controlled robots In fact adding GPIO Zero to this we could make a very cool input device.
  • Assistive technologies, where a user is unable to press keys on a keyboard, we can simulate those keys and enable the user to work with adjusted input devices.

How can I install it?

Using pip
Python 2
sudo pip install keyboard

Python 3
sudo pip3 install keyboard

How can I use it?

Note: Windows users can dive straight in and use the library, for Linux/Unix users you will need to run the code as a root / sudo user as the library directly accesses the /dev/input/input* keyboard device, bypassing X.

Simulate a keypress

First import the library into your Python code

import keyboard

Then you can simulate a keypress as so, here I simulate ctrl + alt + L being pressed to lock my Ubuntu desktop.


Running this code will lock my desktop!

Write a sentence

For the demo I created a function so that I had time to switch windows to enable the output to be seen. Also note that it prints "#sysadmnGREGGS" missing the "i", this is quite common, sadly. I tested on Windows and it was fine.

import keyboard

Wait for a keypress

Waits for the ESC to be pressed before moving on.

import keyboard

Evaluate if a certain key is pressed

When a specified key is pressed, the is_pressed function will report True, other times it will report False.

import keyboard
while True:

Record keystrokes

This will record every keypress until ESC is pressed.

From the creator: This program makes no attempt to hide itself, so don’t use it for keyloggers.

import keyboard
recorded = keyboard.record(until='esc')

Playback keystrokes

import keyboard
keyboard.play(recorded, speed_factor=3)


A handy Python library that has a few quirks, but provides an easy method for keyboard input to be captured, used as input, or recorded to create complex sequences at the touch of a button.