pynput

1.8.1 · active · verified Sat Apr 11

pynput is a Python library that allows you to control and monitor user input devices, specifically the keyboard and mouse. It provides cross-platform functionality for simulating keystrokes and mouse events, as well as listening for input. The current version is 1.8.1, and the library is regularly updated to address platform-specific nuances and improve functionality.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both monitoring keyboard input and controlling mouse actions. A keyboard listener is started in a non-blocking thread, which prints pressed keys until 'Esc' is released. Concurrently, a mouse controller moves the cursor and performs a left-click. The script waits for the keyboard listener to be explicitly stopped by the user.

from pynput import keyboard, mouse
import time

def on_press(key):
    try:
        print(f'Alphanumeric key pressed: {key.char}')
    except AttributeError:
        print(f'Special key pressed: {key}')

def on_release(key):
    print(f'Key released: {key}')
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# --- Keyboard Listener ---
print("Starting keyboard listener. Press 'Esc' to exit.")
keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)
keyboard_listener.start()

# --- Mouse Controller (runs after listener starts) ---
mouse_controller = mouse.Controller()
print(f"Current mouse position: {mouse_controller.position}")

# Move mouse to (100, 100) and click left button
mouse_controller.position = (100, 100)
print(f"Moved mouse to: {mouse_controller.position}")
time.sleep(1)
mouse_controller.click(mouse.Button.left, 1)
print("Left clicked.")

# Wait for keyboard listener to stop
keyboard_listener.join()
print("Keyboard listener stopped.")

view raw JSON →