or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

hotkeys.mdindex.mdinteractive-input.mdkey-simulation.mdkeyboard-events.mdrecording-playback.mdtext-processing.md
tile.json

tessl/pypi-keyboard

Hook and simulate keyboard events on Windows and Linux

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/keyboard@0.13.x

To install, run

npx @tessl/cli install tessl/pypi-keyboard@0.13.0

index.mddocs/

Keyboard

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.

Package Information

  • Package Name: keyboard
  • Language: Python
  • Installation: pip install keyboard
  • Version: 0.13.5
  • Dependencies: Zero dependencies (except pyobjc on macOS)

Core Imports

import keyboard

All functions are available directly from the main module:

from keyboard import add_hotkey, wait, write, record, play

Basic Usage

import keyboard

# Simple key simulation
keyboard.write('Hello World!')
keyboard.press_and_release('shift+s, space')

# Register hotkeys
keyboard.add_hotkey('ctrl+shift+a', print, args=('Hotkey triggered!',))

# Global event monitoring
def on_key_event(event):
    print(f'Key {event.name} was {"pressed" if event.event_type == "down" else "released"}')

keyboard.hook(on_key_event)

# Block until ESC is pressed
keyboard.wait('esc')

# Record and replay
recorded = keyboard.record(until='esc')
keyboard.play(recorded, speed_factor=2.0)

# Text abbreviations
keyboard.add_abbreviation('@@', 'user@example.com')

Architecture

The keyboard package is built on a platform-specific listener architecture:

  • Event System: Global keyboard hooks capture all key events regardless of window focus
  • Cross-Platform: Platform-specific implementations for Windows (_winkeyboard), Linux (_nixkeyboard), and macOS (_darwinkeyboard)
  • Thread Safety: Event capture runs in separate threads to avoid blocking the main program
  • State Management: Tracks pressed keys, modifier states, and event suppression
  • Hotkey Engine: Complex multi-step hotkey parsing with timeout support

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.

Capabilities

Keyboard Event Capture

Global keyboard event monitoring and hooking system for capturing all keyboard activity system-wide, including key press/release detection, modifier tracking, and event filtering.

def hook(callback, suppress=False, on_remove=lambda: None): ...
def on_press(callback, suppress=False): ...
def on_release(callback, suppress=False): ...
def hook_key(key, callback, suppress=False): ...
def unhook(remove): ...
def unhook_all(): ...

Keyboard Events

Key Simulation and Text Input

Programmatic key press simulation, text typing with unicode support, and keyboard state management for automating keyboard input.

def send(hotkey, do_press=True, do_release=True): ...
def press(hotkey): ...
def release(hotkey): ...
def write(text, delay=0, restore_state_after=True, exact=None): ...
def is_pressed(hotkey): ...

Key Simulation

Hotkey Management

Registration and management of complex keyboard shortcuts, including multi-step hotkeys, global hotkey detection, and key remapping capabilities.

def add_hotkey(hotkey, callback, args=(), suppress=False, timeout=1, trigger_on_release=False): ...
def remove_hotkey(hotkey_or_callback): ...
def remap_hotkey(src, dst, suppress=True, trigger_on_release=False): ...
def block_key(key): ...
def get_hotkey_name(names=None): ...

Hotkeys

Recording and Playback

Capture sequences of keyboard events and replay them later, supporting timing control and selective event filtering for automation and testing.

def record(until='escape', suppress=False, trigger_on_release=False): ...
def play(events, speed_factor=1.0): ...
def start_recording(recorded_events_queue=None): ...
def stop_recording(): ...

Recording and Playback

Text Processing and Abbreviations

Advanced text input processing including word detection, automatic text replacement, typed string extraction, and abbreviation expansion.

def add_word_listener(word, callback, triggers=['space'], match_suffix=False, timeout=2): ...
def add_abbreviation(source_text, replacement_text, match_suffix=False, timeout=2): ...
def get_typed_strings(events, allow_backspace=True): ...
def remove_word_listener(word_or_handler): ...

Text Processing

Interactive Input Reading

Blocking functions for reading keyboard input in interactive applications, including single key reading, hotkey detection, and event waiting.

def wait(hotkey=None, suppress=False, trigger_on_release=False): ...
def read_event(suppress=False): ...
def read_key(suppress=False): ...
def read_hotkey(suppress=True): ...

Interactive Input

Core Types

class KeyboardEvent:
    """Represents a keyboard event with timing and key information."""
    event_type: str  # 'down' or 'up'
    scan_code: int   # Physical key scan code
    name: str        # Key name (normalized)
    time: float      # Event timestamp
    device: int      # Device identifier (platform-specific)
    modifiers: list  # Active modifier keys
    is_keypad: bool  # True if from numeric keypad
    
    def to_json(self, ensure_ascii=False) -> str: ...

# Package metadata
version: str = '0.13.5'  # Package version string

# Event type constants
KEY_DOWN: str = 'down'
KEY_UP: str = 'up'

# Modifier key sets
all_modifiers: set      # All modifier key names including sided variants
sided_modifiers: set    # Base modifier names: {'ctrl', 'alt', 'shift', 'windows'}

# Key normalization and utilities
def normalize_name(name: str) -> str: ...
def is_modifier(key) -> bool: ...
def key_to_scan_codes(key, error_if_missing=True) -> tuple: ...
def parse_hotkey(hotkey) -> tuple: ...

Function Aliases

The keyboard package provides multiple aliases for many functions to support different naming conventions and use cases:

# Key simulation aliases
press_and_release = send  # Alternative name for send()

# Hotkey management aliases  
register_hotkey = add_hotkey           # Alternative registration function
clear_hotkey = remove_hotkey           # Alternative removal function
unregister_hotkey = remove_hotkey      # Alternative removal function
unremap_hotkey = remove_hotkey         # Remove hotkey remapping

# Hotkey cleanup aliases
clear_all_hotkeys = unhook_all_hotkeys       # Alternative cleanup function
remove_all_hotkeys = unhook_all_hotkeys      # Alternative cleanup function  
unregister_all_hotkeys = unhook_all_hotkeys  # Alternative cleanup function

# Key management aliases
unhook_key = unhook        # Remove key hook
unblock_key = unhook_key   # Remove key block
unremap_key = unhook_key   # Remove key remapping

# Recording/playback aliases
replay = play  # Alternative name for play()

# Text processing aliases
register_word_listener = add_word_listener        # Alternative registration
register_abbreviation = add_abbreviation          # Alternative registration
remove_abbreviation = remove_word_listener        # Remove abbreviation

Key Features

  • Global Event Capture: Monitors all keyboard activity regardless of window focus
  • Cross-Platform: Native support for Windows, Linux, and macOS
  • Zero Dependencies: Pure Python implementation (except macOS)
  • Complex Hotkeys: Multi-step hotkey sequences with customizable timeouts
  • Unicode Support: Full internationalization with proper keyboard layout mapping
  • Thread Safe: Non-blocking event capture in separate threads
  • Event Suppression: Ability to block keys and remap functionality (platform-dependent)
  • Recording/Playback: Complete keyboard session capture and replay
  • Text Automation: Advanced text replacement and abbreviation systems

Platform Considerations

  • Windows: Full functionality including event suppression and device identification
  • Linux: Requires root privileges for global hooks, limited device information
  • macOS: Experimental support, requires pyobjc dependency, some limitations with event suppression

The package automatically detects the platform and loads the appropriate implementation, providing a consistent API across all supported operating systems.