Keyboard Library Python: Complete Guide to Keyboard Control

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction

Automating keyboard input and handling keyboard events are essential for application testing, custom scripts, and utility tools. Whether you need to programmatically press keys, respond to user input, or create custom hotkeys, Python offers an excellent library called keyboard.

The keyboard library is a powerful cross-platform tool that lets you control the keyboard at the operating system level. It works as both a listener and event generator — you can intercept real keyboard input and simulate keystrokes programmatically.

In this guide, we'll dive deep into the keyboard library, from installation to advanced use cases like macros, global hotkeys, key loggers, and combo command handling.

Installation & Requirements

Install the library via pip:

pip install keyboard

System Requirements

Windows: Works out of the box with no extra configuration.

Linux: Requires root access to capture global keyboard events. Run your script with sudo for full functionality.

macOS: Partially restricted; you must grant accessibility permissions in System Preferences > Security & Privacy > Privacy > Accessibility.

Core Features of the Keyboard Library

The keyboard library offers a wide range of functions for keyboard control:

Key Press Simulation

Programmatically simulate key presses to automate repetitive tasks.

Keyboard Event Hooking

Monitor real-time key presses and create custom event handlers.

Global Hotkeys

Register global keyboard shortcuts to trigger functions instantly.

Macro Recording & Playback

Record a sequence of keystrokes and replay them later.

Basic Key Simulation Functions

Typing Text

import keyboard

# Simple text input
keyboard.write("Hello, world!")

# Typing with a delay between characters
keyboard.write("Slow typing", delay=0.1)

Pressing and Releasing Keys

# Press a key (hold it down)
keyboard.press("ctrl")

# Release a key
keyboard.release("ctrl")

# Press and immediately release
keyboard.press_and_release("enter")

Key Combinations

# Send a keyboard shortcut
keyboard.send("ctrl+c")
keyboard.send("ctrl+shift+n")

# Alternative method
keyboard.press("ctrl")
keyboard.press("c")
keyboard.release("c")
keyboard.release("ctrl")

Working with Hotkeys

Registering Hotkeys

import keyboard

def launch_notepad():
    print("Launching Notepad!")
    # Add code to open the app here

# Register a hotkey
keyboard.add_hotkey("ctrl+alt+n", launch_notepad)

# Wait for Esc key to exit
keyboard.wait("esc")

Multiple Key Combinations

# A sequence of key presses
keyboard.add_hotkey("ctrl+alt+a, ctrl+alt+b", lambda: print("Complex combo triggered!"))

Managing Hotkeys

# Remove a specific hotkey
hotkey = keyboard.add_hotkey("ctrl+space", lambda: print("Hotkey!"))
keyboard.remove_hotkey(hotkey)

# Clear all registered hotkeys
keyboard.clear_hotkeys()

Handling Keyboard Events

Tracking Key Presses

def on_key_press(event):
    print(f"Key pressed: {event.name}")

def on_key_release(event):
    print(f"Key released: {event.name}")

# Hook into keyboard events
keyboard.on_press(on_key_press)
keyboard.on_release(on_key_release)

# Keep the script running
keyboard.wait()

Recording and Playing Back Macros

# Record keystrokes until Esc is pressed
recorded = keyboard.record(until="esc")

# Play back the recorded sequence
keyboard.play(recorded, speed_factor=1.0)

Advanced Use Cases

Creating a Simple Keylogger

import keyboard

def log_key(event):
    with open("keylog.txt", "a") as f:
        f.write(f"{event.name}\n")

keyboard.on_press(log_key)
keyboard.wait()

Building a Macro Recorder

import keyboard
import time

def record_macro():
    print("Recording... Press F9 to stop.")
    events = []
    while True:
        event = keyboard.read_event()
        if event.event_type == "down":
            events.append((event.name, time.time()))
            if event.name == "f9":
                break
    return events

def play_macro(events):
    for i, (key, timestamp) in enumerate(events):
        if i > 0:
            delay = timestamp - events[i-1][1]
            time.sleep(delay)
        keyboard.press_and_release(key)

Troubleshooting Common Issues

Permission Errors on Linux/macOS

If you get permission errors, run your script with elevated privileges:

sudo python your_script.py

Keys Not Being Detected

Make sure no other application is blocking keyboard input. On macOS, verify that your terminal or IDE has accessibility permissions enabled.

Conflicts with Other Libraries

The keyboard library may conflict with pynput or pyautogui if they try to hook the same events. Use only one library for keyboard control at a time.

Conclusion

The Python keyboard library is a versatile tool for automating keyboard input, creating hotkeys, and handling events. Whether you're building a macro tool, a game bot, or a productivity script, this library has you covered.

Start experimenting with the examples above, and you'll be automating your keyboard in no time!

Recommendations