pynput
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
- breaking macOS Security Permissions: On recent macOS versions, monitoring keyboard input requires explicit user permission via 'Enable access for assistive devices' in System Preferences. Without this, keyboard listeners will not receive events. For scripts run from a terminal, the terminal application itself might need to be whitelisted.
- gotcha Listener Callbacks and Blocking Operations: Listener callbacks (e.g., `on_press`, `on_move`) are invoked in a separate thread. Performing long-running or blocking operations directly within these callbacks can freeze input for the entire system.
- gotcha Non-blocking Listeners and Program Termination: If a `Listener` is started using `listener.start()` without a subsequent `listener.join()` or keeping the main thread alive, the program may terminate immediately as the main thread exits, stopping the daemon listener thread.
- gotcha Windows Virtual Key Event Limitations: On Windows, virtual events sent by `pynput.keyboard.Controller` might not always behave identically to physical key presses. Specifically, key press events may not be continuously emitted when 'held down', and complex combinations like Shift + Arrow keys might not work as expected.
- gotcha Linux SSH/Remote Execution: Running `pynput` listeners or controllers over SSH without X forwarding or setting the `$DISPLAY` environment variable will generally not work, as it requires an active X server.
- gotcha PyCharm/Virtual Environment Issues: Users sometimes report `ImportError` in IDEs like PyCharm even after `pip install pynput`. This is often due to PyCharm's project interpreter not being configured to use the correct Python environment where pynput was installed (e.g., using a project-specific virtual environment instead of global site-packages).
Install
-
pip install pynput
Imports
- keyboard
from pynput import keyboard
- mouse
from pynput import mouse
- Listener (keyboard)
from pynput.keyboard import Listener
- Controller (keyboard)
from pynput.keyboard import Controller
- Key
from pynput.keyboard import Key
- Listener (mouse)
from pynput.mouse import Listener
- Controller (mouse)
from pynput.mouse import Controller
- Button
from pynput.mouse import Button
Quickstart
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.")