keyboard

repository·master·Indexed 26 days ago

https://github.com/boppreh/keyboard

A lightweight Python library for global keyboard control on Windows and Linux. It provides a high-level API to simulate key presses, register hotkeys, record and replay events, and install global keyboard listeners via hooks. Key features include the ability to block or remap keys, add abbreviations, and use word listeners to trigger callbacks when specific text sequences are typed.

Tokens
3.5K
Snippets
13
Records
28
Agent score
37%

What's inside keyboard

  1. Install the keyboard library

    master

    You can install the keyboard library via PyPI using pip, or by cloning the repository directly. Since it is a pure Python library with zero dependencies, you can also simply copy the source files into your project.

    pip install keyboard
  2. Correctly invoking code with add_hotkey

    master

    When using keyboard.add_hotkey(key, callback), ensure the callback is a function or a lambda. Passing a function call directly (e.g., keyboard.add_hotkey('space', print('pressed'))) will execute the function immediately during registration rather than when the key is pressed.

    import keyboard
    
    # DO THIS:
    keyboard.add_hotkey('space', lambda: print('space was pressed'))
    
    # OR THIS:
    def on_space():
        print('space was pressed')
    keyboard.add_hotkey('space', on_space)
  3. Avoid high CPU usage when waiting for keys

    master

    When waiting for a key press or a specific state, avoid using busy-wait loops (e.g., while not keyboard.is_pressed('space'): pass) as they will consume 100% of your CPU.

    Instead, use keyboard.wait(key) which blocks efficiently, or use keyboard.add_hotkey() to trigger logic via an event callback.

    import keyboard
    
    # DO THIS (Efficient):
    keyboard.wait('space')
    print('space was pressed, continuing...')
    
    # OR THIS (Event-driven):
    keyboard.add_hotkey('space', lambda: print('space was pressed!'))
    keyboard.wait()
  4. Use keyboard as a Python library

    master

    The keyboard library provides a high-level API to simulate key presses, register hotkeys, and record/replay events.

    Common tasks include:

    • press_and_release(key_combination): Simulates a key press and release.
    • write(string): Types a string of text.
    • add_hotkey(hotkey, callback, *args): Registers a function to run when a specific key combination is pressed.
    • wait(key): Blocks execution until a specific key is pressed.
    • record(until=key): Records keyboard events until the specified key is pressed.
    • play(recorded_events, speed_factor=1): Replays recorded events at a specified speed.
    • add_abbreviation(trigger, replacement): Replaces a specific sequence of characters with a predefined string.
    import keyboard
    
    # Simulate key presses
    keyboard.press_and_release('shift+s, space')
    keyboard.write('The quick brown fox jumps over the lazy dog.')
    
    # Register hotkeys
    keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey'))
    keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))
    
    # Wait for a key
    keyboard.wait('esc')
    
    # Record and replay
    recorded = keyboard.record(until='esc')
    keyboard.play(recorded, speed_factor=3)
    
    # Abbreviations
    keyboard.add_abbreviation('@@', 'my.long.email@example.com')
    
    # Block forever
    keyboard.wait()
  5. Install global keyboard listeners with hook()

    master

    Installs a global listener on all available keyboards. The provided callback is invoked for every key press or release.

    The event passed to the callback is a keyboard.KeyboardEvent object with these attributes:

    • name: Lower-case Unicode representation of the character (e.g. "&") or description (e.g. "space").
    • scan_code: The physical key number (e.g. 55).
    • time: Timestamp of the event with OS-provided precision.

    Options:

    • suppress (bool): If true, prevents the event from being passed to other applications. Defaults to False.
    • on_remove (callable): A lambda or function to call when the hook is removed.
  6. Block or remap keys

    master

    Modify keyboard behavior:

    • block_key(key): Suppresses all key events for the given key, regardless of modifiers.
    • remap_key(src, dst): Whenever src is pressed or released, the hotkey dst is pressed or released instead.
    • remap_hotkey(src, dst, suppress=True, trigger_on_release=False): Whenever the hotkey src is pressed, it is suppressed and dst is sent instead.
    remap('alt+w', 'ctrl+up')
  7. Record and play keyboard events

    master

    You can record a sequence of keyboard actions and replay them later using record() and play().

    • record(until='escape', suppress=False, trigger_on_release=False): A blocking function that records all keyboard events until the specified until hotkey is pressed. Returns a list of keyboard.KeyboardEvent objects.
    • play(events, speed_factor=1.0): Replays a list of events. If speed_factor is <= 0, events are replayed as fast as the OS allows. The current keyboard state is cleared at the start and restored at the end.
  8. Listen for specific key events with on_press() and on_release()

    master

    Specialized hooks for specific event types:

    • on_press(callback, suppress=False): Invokes the callback for every KEY_DOWN event.
    • on_release(callback, suppress=False): Invokes the callback for every KEY_UP event.
  9. Simulate typing with write()

    master

    Sends artificial keyboard events to simulate typing text. Characters not on the keyboard are typed using OS-specific unicode methods (e.g., alt+codepoint).

    To ensure integrity, all currently pressed keys are released before typing, and modifiers are restored afterward.

    Options:

    • delay (float): Seconds to wait between keypresses. Defaults to 0.
    • restore_state_after (bool): If true, restores the state of keys that were released at the start. Defaults to True.
    • exact (any): If set, forces all characters to be typed as explicit unicode. If None, uses platform-specific suggestions.
  10. Execute a function later with call_later()

    master
    Calls the provided function in a new thread after a specified delay (in seconds). This is useful for allowing the system time to process an event without blocking the current execution flow.
  11. Manage and remove hooks

    master

    Use these functions to clean up listeners:

    • unhook(remove): Removes a hook using the callback or the handler returned by hook().
    • unhook_all(): Removes all keyboard hooks, including hotkeys, abbreviations, word listeners, recorders, and waits.
    • unhook_all_hotkeys(): Removes all keyboard hotkeys, including abbreviations, word listeners, recorders, and waits.
  12. Register hotkeys with add_hotkey()

    master

    Invokes a callback every time a specific hotkey sequence is detected. The callback is executed asynchronously in a separate thread.

    Hotkeys must follow the format ctrl+shift+a, s (e.g., hold ctrl, shift, and 'a', release, then press 's'). To use literal characters like commas or pluses, use their names (e.g., 'comma', 'plus').

    Options:

    • args (list): Optional arguments passed to the callback.
    • suppress (bool): If true, successful triggers block keys from being sent to other programs. Defaults to False.
    • timeout (float): Seconds allowed between key presses. Defaults to 1.
    • trigger_on_release (bool): If true, callback triggers on key release instead of press. Defaults to False.

    To remove a hotkey, use remove_hotkey(hotkey) or remove_hotkey(handler) using the returned handler.

    # Different but equivalent ways to listen for a spacebar key press.
    add_hotkey(' ', print, args=['space was pressed'])
    add_hotkey('space', print, args=['space was pressed'])
    add_hotkey('Space', print, args=['space was pressed'])
    # Using scan code 57 for spacebar
    add_hotkey(57, print, args=['space was pressed'])
    
    add_hotkey('ctrl+q', quit)
    add_hotkey('ctrl+alt+enter, space', some_callback)