Guide to Python's keyboard Module

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 keyloggers 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 Linnux, in order to use this library, you must install it as root . If you don't, you'll get an:
Also, when running your script, you should run it with root privileges:
On Windows and MacOS, as the privileges work much differently — you can install it simply via pip and run the scripts:
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:
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 commmand and executing it:
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:
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!
However, you can hold down some special keys, such as [SHIFT] or [CTRL] this way:
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 key loggers.
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:
If we're to print the recorded_events , they'd look something like:
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:
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:
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] :
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:
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.
keyboard
Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.
Features
- Global event hook on all keyboards (captures keys regardless of focus).
- Listen and send keyboard events.
- Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!).
- Pure Python, no C modules to be compiled.
- Zero dependencies. Trivial to install and deploy, just copy the files.
- Python 2 and 3.
- Complex hotkey support (e.g. ctrl+shift+m, ctrl+space ) with controllable timeout.
- Includes high level API (e.g. record and play, add_abbreviation).
- Maps keys as they actually are in your layout, with full internationalization support (e.g. Ctrl+ç ).
- Events automatically captured in separate thread, doesn’t block main program.
- Tested and documented.
- Doesn’t break accented dead keys (I’m looking at you, pyHook).
- Mouse support available via project mouse ( pip install mouse ).
Usage
or clone the repository (no installation required, source files are sufficient):
Установил модуль "keyboard", а python его не видит [закрыт]
Вопрос вызван проблемой, которая больше не воспроизводится, или опечаткой. Хотя похожие вопросы могут быть уместны на этом сайте, решение для этого вопроса вряд ли поможет будущим посетителям. Обычно можно избежать подобных вопросов написанием и исследованием минимальной программы для воспроизведения проблемы до публикации вопроса.
Закрыт 2 года назад .
Я установил модуль "keyboard", а Python его не видит.
Импортировал модуль я так:
Но как бы я не старался переустанавливать модуль стандартный IDLE его не видит, как это можно исправить?
Проблема скорее всего появилась когда я устанавливал новую версию Python
Мои попытки установки и переустановки:
Только-что попробовал запустить Python файл через cmd и каким-то чудом он не стал жаловаться на отсутствие библиотеки и просто заработал. Всё-таки я хочу разобраться почему так происходит. Помогите пожалуйста!
1 вариант решения: Чтобы Python увидел библиотеку запускать скрипт нужно через командную строку (cmd). Не знаю как так происходило, но оно так работало.
2 вариант решения: Так-же работает вариант переустановить систему и последующая установка чистейшего Python на новую систему, тогда внутри системы Python перестанет конфликтовать сам с собой или с системой. Незнаю как так получилось, но это скорее всего конфликт Python с чем-то что мне не ведомо)
Мне помогло лишь переустановить полностью систему, тем самым конфликты системы с Python видимо исчезли и он стал нормально воспринимать установленную мной библиотеку "keyboard" [Ранее я уже пробовал переустанавливать Python или откатываться назад на предыдущие версии (может там что-то бы заработало), но нечего не помогало, лишь переустановка системы (Что достаточно радикально!), помогло мне справиться с проблемой.]
Это одиночная ошибка которую я допустил я сам и из-за этого скорее всего подобных случаев не будет происходить с другими людьми, было неправильно задавать такой вопрос здесь)
Как установить keyboard python
Hook and simulate global keyboard events on Windows and Linux.
- License: MIT
- Home: https://github.com/boppreh/keyboard
- Development: https://github.com/boppreh/keyboard
- Documentation: https://github.com/boppreh/keyboard#api
- 15037 total downloads
- Last upload: 4 months and 20 days ago
Installers
- linux-64 v0.13.5
- osx-64 v0.13.5
- win-64 v0.13.5
conda install
Description
Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.