pynput: A Cross-Platform Python Library for Controlling and Monitoring Keyboard and Mouse

What is pynput?

pynput is a cross-platform Python library specifically designed for controlling (Ctrl) and monitoring (Monitor) keyboard and mouse.

  • Cross-Platform: macOS, Windows, Linux (default xorg, Linux can also use uinput).
  • Two Main Subpackages: <span>pynput.mouse</span> and <span>pynput.keyboard</span>, all classes are directly under the root package, so you can use it with <span>from pynput import mouse, keyboard</span>.
  • Underlying Principle: Calls system-level APIs (Win32, Cocoa, X11, etc.), no additional drivers or administrator permissions required (except for Linux uinput).

In simple terms, it allows you to write scripts to automatically click the mouse, type on the keyboard, or capture user input in real-time, thus enabling various needs such as automated testing, macro scripts, game cheats, accessibility tools, etc.

What Pain Points Does It Address?

Traditional Approach Pain Points pynput’s Solution
Manual Operation High repetition, prone to errors Use code to “get it done with one click”, precise and repeatable
Windows API (C++) High learning curve, poor cross-platform support Python calls, unified cross-platform interface
Third-Party Tools (AutoHotkey, Sikuli) Dependency on external software, difficult to maintain scripts Pure Python package, directly written into the project
Listening to Keyboard/Mouse Events Requires writing low-level callbacks, troublesome thread management <span>Listener</span> runs automatically in the background thread, returning <span>True/False</span> to control stopping
Keyboard Macros Can only be used within specific software Global hotkeys (<span>GlobalHotKeys</span>) respond at any time

Installation & Quick Start

pip install pynput

Note: If you want to use <span>uinput</span> on Linux, you need to run <span>sudo apt install python3-uinput</span> and run the script as an administrator. In most cases, using the default <span>xorg</span> is sufficient.

Basic Usage Example

# Control Mouse
from pynput.mouse import Button, Controller
mouse = Controller()
mouse.position = (100, 200)          # Move to specified coordinates
mouse.click(Button.left, 2)          # Double-click left button
mouse.scroll(0, -3)                  # Scroll down three units

# Listen to Mouse
from pynput import mouse

def on_move(x, y):
    print(f'Mouse moved to {x},{y}')

def on_click(x, y, button, pressed):
    print(f'{

Leave a Comment