Hook and simulate keyboard events on Windows and Linux
npx @tessl/cli install tessl/pypi-keyboard@0.13.00
# Keyboard
1
2
A comprehensive cross-platform Python library for capturing global keyboard events and simulating keyboard input. The keyboard package provides pure Python functionality with zero dependencies, supporting Windows, Linux, and macOS for both monitoring and controlling keyboard interactions programmatically.
3
4
## Package Information
5
6
- **Package Name**: keyboard
7
- **Language**: Python
8
- **Installation**: `pip install keyboard`
9
- **Version**: 0.13.5
10
- **Dependencies**: Zero dependencies (except pyobjc on macOS)
11
12
## Core Imports
13
14
```python
15
import keyboard
16
```
17
18
All functions are available directly from the main module:
19
20
```python
21
from keyboard import add_hotkey, wait, write, record, play
22
```
23
24
## Basic Usage
25
26
```python
27
import keyboard
28
29
# Simple key simulation
30
keyboard.write('Hello World!')
31
keyboard.press_and_release('shift+s, space')
32
33
# Register hotkeys
34
keyboard.add_hotkey('ctrl+shift+a', print, args=('Hotkey triggered!',))
35
36
# Global event monitoring
37
def on_key_event(event):
38
print(f'Key {event.name} was {"pressed" if event.event_type == "down" else "released"}')
39
40
keyboard.hook(on_key_event)
41
42
# Block until ESC is pressed
43
keyboard.wait('esc')
44
45
# Record and replay
46
recorded = keyboard.record(until='esc')
47
keyboard.play(recorded, speed_factor=2.0)
48
49
# Text abbreviations
50
keyboard.add_abbreviation('@@', 'user@example.com')
51
```
52
53
## Architecture
54
55
The keyboard package is built on a platform-specific listener architecture:
56
57
- **Event System**: Global keyboard hooks capture all key events regardless of window focus
58
- **Cross-Platform**: Platform-specific implementations for Windows (`_winkeyboard`), Linux (`_nixkeyboard`), and macOS (`_darwinkeyboard`)
59
- **Thread Safety**: Event capture runs in separate threads to avoid blocking the main program
60
- **State Management**: Tracks pressed keys, modifier states, and event suppression
61
- **Hotkey Engine**: Complex multi-step hotkey parsing with timeout support
62
63
The package handles keyboard layout internationalization, maps keys according to actual keyboard layouts, and provides both high-level convenience functions and low-level event access.
64
65
## Capabilities
66
67
### Keyboard Event Capture
68
69
Global keyboard event monitoring and hooking system for capturing all keyboard activity system-wide, including key press/release detection, modifier tracking, and event filtering.
70
71
```python { .api }
72
def hook(callback, suppress=False, on_remove=lambda: None): ...
73
def on_press(callback, suppress=False): ...
74
def on_release(callback, suppress=False): ...
75
def hook_key(key, callback, suppress=False): ...
76
def unhook(remove): ...
77
def unhook_all(): ...
78
```
79
80
[Keyboard Events](./keyboard-events.md)
81
82
### Key Simulation and Text Input
83
84
Programmatic key press simulation, text typing with unicode support, and keyboard state management for automating keyboard input.
85
86
```python { .api }
87
def send(hotkey, do_press=True, do_release=True): ...
88
def press(hotkey): ...
89
def release(hotkey): ...
90
def write(text, delay=0, restore_state_after=True, exact=None): ...
91
def is_pressed(hotkey): ...
92
```
93
94
[Key Simulation](./key-simulation.md)
95
96
### Hotkey Management
97
98
Registration and management of complex keyboard shortcuts, including multi-step hotkeys, global hotkey detection, and key remapping capabilities.
99
100
```python { .api }
101
def add_hotkey(hotkey, callback, args=(), suppress=False, timeout=1, trigger_on_release=False): ...
102
def remove_hotkey(hotkey_or_callback): ...
103
def remap_hotkey(src, dst, suppress=True, trigger_on_release=False): ...
104
def block_key(key): ...
105
def get_hotkey_name(names=None): ...
106
```
107
108
[Hotkeys](./hotkeys.md)
109
110
### Recording and Playback
111
112
Capture sequences of keyboard events and replay them later, supporting timing control and selective event filtering for automation and testing.
113
114
```python { .api }
115
def record(until='escape', suppress=False, trigger_on_release=False): ...
116
def play(events, speed_factor=1.0): ...
117
def start_recording(recorded_events_queue=None): ...
118
def stop_recording(): ...
119
```
120
121
[Recording and Playback](./recording-playback.md)
122
123
### Text Processing and Abbreviations
124
125
Advanced text input processing including word detection, automatic text replacement, typed string extraction, and abbreviation expansion.
126
127
```python { .api }
128
def add_word_listener(word, callback, triggers=['space'], match_suffix=False, timeout=2): ...
129
def add_abbreviation(source_text, replacement_text, match_suffix=False, timeout=2): ...
130
def get_typed_strings(events, allow_backspace=True): ...
131
def remove_word_listener(word_or_handler): ...
132
```
133
134
[Text Processing](./text-processing.md)
135
136
### Interactive Input Reading
137
138
Blocking functions for reading keyboard input in interactive applications, including single key reading, hotkey detection, and event waiting.
139
140
```python { .api }
141
def wait(hotkey=None, suppress=False, trigger_on_release=False): ...
142
def read_event(suppress=False): ...
143
def read_key(suppress=False): ...
144
def read_hotkey(suppress=True): ...
145
```
146
147
[Interactive Input](./interactive-input.md)
148
149
## Core Types
150
151
```python { .api }
152
class KeyboardEvent:
153
"""Represents a keyboard event with timing and key information."""
154
event_type: str # 'down' or 'up'
155
scan_code: int # Physical key scan code
156
name: str # Key name (normalized)
157
time: float # Event timestamp
158
device: int # Device identifier (platform-specific)
159
modifiers: list # Active modifier keys
160
is_keypad: bool # True if from numeric keypad
161
162
def to_json(self, ensure_ascii=False) -> str: ...
163
164
# Package metadata
165
version: str = '0.13.5' # Package version string
166
167
# Event type constants
168
KEY_DOWN: str = 'down'
169
KEY_UP: str = 'up'
170
171
# Modifier key sets
172
all_modifiers: set # All modifier key names including sided variants
173
sided_modifiers: set # Base modifier names: {'ctrl', 'alt', 'shift', 'windows'}
174
175
# Key normalization and utilities
176
def normalize_name(name: str) -> str: ...
177
def is_modifier(key) -> bool: ...
178
def key_to_scan_codes(key, error_if_missing=True) -> tuple: ...
179
def parse_hotkey(hotkey) -> tuple: ...
180
```
181
182
## Function Aliases
183
184
The keyboard package provides multiple aliases for many functions to support different naming conventions and use cases:
185
186
```python { .api }
187
# Key simulation aliases
188
press_and_release = send # Alternative name for send()
189
190
# Hotkey management aliases
191
register_hotkey = add_hotkey # Alternative registration function
192
clear_hotkey = remove_hotkey # Alternative removal function
193
unregister_hotkey = remove_hotkey # Alternative removal function
194
unremap_hotkey = remove_hotkey # Remove hotkey remapping
195
196
# Hotkey cleanup aliases
197
clear_all_hotkeys = unhook_all_hotkeys # Alternative cleanup function
198
remove_all_hotkeys = unhook_all_hotkeys # Alternative cleanup function
199
unregister_all_hotkeys = unhook_all_hotkeys # Alternative cleanup function
200
201
# Key management aliases
202
unhook_key = unhook # Remove key hook
203
unblock_key = unhook_key # Remove key block
204
unremap_key = unhook_key # Remove key remapping
205
206
# Recording/playback aliases
207
replay = play # Alternative name for play()
208
209
# Text processing aliases
210
register_word_listener = add_word_listener # Alternative registration
211
register_abbreviation = add_abbreviation # Alternative registration
212
remove_abbreviation = remove_word_listener # Remove abbreviation
213
```
214
215
## Key Features
216
217
- **Global Event Capture**: Monitors all keyboard activity regardless of window focus
218
- **Cross-Platform**: Native support for Windows, Linux, and macOS
219
- **Zero Dependencies**: Pure Python implementation (except macOS)
220
- **Complex Hotkeys**: Multi-step hotkey sequences with customizable timeouts
221
- **Unicode Support**: Full internationalization with proper keyboard layout mapping
222
- **Thread Safe**: Non-blocking event capture in separate threads
223
- **Event Suppression**: Ability to block keys and remap functionality (platform-dependent)
224
- **Recording/Playback**: Complete keyboard session capture and replay
225
- **Text Automation**: Advanced text replacement and abbreviation systems
226
227
## Platform Considerations
228
229
- **Windows**: Full functionality including event suppression and device identification
230
- **Linux**: Requires root privileges for global hooks, limited device information
231
- **macOS**: Experimental support, requires pyobjc dependency, some limitations with event suppression
232
233
The package automatically detects the platform and loads the appropriate implementation, providing a consistent API across all supported operating systems.