Keyboard: Global Keyboard Events and Simulation
The `keyboard` library for Python provides full control over the keyboard, allowing users to hook global events, register hotkeys, simulate key presses, and much more. It works on Windows and Linux, with experimental support for macOS. The current version is 0.13.5, and it maintains an active development and release cadence.
Warnings
- gotcha On Linux, the `keyboard` library often requires root privileges (sudo) to access raw keyboard device files, leading to an `ImportError: You must be root to use this library on linux.` if not run with elevated permissions.
- gotcha On macOS, `keyboard` support is experimental and requires granting Accessibility permissions to your terminal or IDE. It may also require running with `sudo` for global event hooks. Some users have reported issues with alphanumeric key simulation on certain Python/macOS versions.
- breaking Starting from version 0.13.0, event names reported by the library now match the *character typed* rather than the physical key. For example, pressing '1' with Shift will report as '!' instead of '1' for functions like `get_typed_strings`.
- gotcha Due to a dependency issue in early 0.13.x releases (specifically 0.13.1), users upgrading might encounter installation problems if pip used a cached version.
- gotcha Mixing `keyboard` with Python's built-in `input()` function or other console input/output libraries can lead to unpredictable behavior or interference, as both attempt to manage input streams independently.
Install
-
pip install keyboard
Imports
- keyboard
import keyboard
Quickstart
import keyboard
import time
# Simulate pressing Shift+S then Space
keyboard.press_and_release('shift+s, space')
# Type a sentence
keyboard.write('The quick brown fox jumps over the lazy dog.')
# Register a hotkey (Ctrl+Shift+A) to print a message
keyboard.add_hotkey('ctrl+shift+a', print, args=('Ctrl+Shift+A triggered',))
# Register a hotkey for a sequence (Page Up then Page Down) to type text
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))
print("Press Ctrl+Shift+A or Page Up then Page Down. Press 'esc' to exit.")
# Blocks until 'esc' is pressed
keyboard.wait('esc')