2 min read

Python Keyboard Module

The keyboard module allows you to take full control of your keyboard. It can hook global events, register hotkeys, simulate key presses, and much more.

Note: This module often requires root/administrator privileges to function correctly, especially on Linux and macOS.

Installation

pip install keyboard

Importing the Module

import keyboard

Listening for Events

on_press()

Invokes a callback for every key press event.

import keyboard

def on_key_event(e):
    print(f"Key {e.name} was pressed")

keyboard.on_press(on_key_event)

# Keep the program running until 'esc' is pressed
keyboard.wait('esc')

wait()

Blocks the program execution until a specific key is pressed.

print("Press 'space' to continue...")
keyboard.wait('space')

Checking Key State

is_pressed()

Returns True if the key is currently pressed.

if keyboard.is_pressed('ctrl'):
    print("Control key is being held down")

Simulating Keystrokes

write()

Types a string.

keyboard.write("Hello World!")

press_and_release()

Simulates pressing and releasing a key or a combination of keys.

keyboard.press_and_release('shift+s, space')
keyboard.press_and_release('ctrl+c')

Hotkeys

add_hotkey()

Invokes a callback when a hotkey is pressed.

def on_hotkey():
    print("Hotkey triggered!")

keyboard.add_hotkey('ctrl+shift+a', on_hotkey)

keyboard.wait('esc')

Recording and Replaying

You can record keyboard activity and replay it later.

# Record until 'esc' is pressed
events = keyboard.record('esc')

# Replay the recorded events
keyboard.play(events)

programming/python/python