How to Control and Monitor Mouse & Keyboard with Python’s pynput Library
This guide explains how the Python pynput library lets you programmatically control mouse movements, clicks, and scrolling, as well as keyboard presses, and how to set up listeners to monitor these input events, including thread handling and stopping mechanisms.
This library lets you control and monitor input devices such as mouse, touchpad, and keyboard.
Each device type is provided as a subpackage:
pynput.mouse – classes for controlling and listening to mouse or touchpad events.
pynput.keyboard – classes for controlling and listening to keyboard events.
Import the subpackages directly from pynput: from pynput import mouse, keyboard Controlling the mouse
Use pynput.mouse.Controller to move the cursor, click buttons, or scroll.
Listening to mouse events
Instantiate pynput.mouse.Listener with callbacks for move, click, and scroll; the listener runs in a separate thread. Call .stop(), raise StopException, or return False from a callback to stop listening.
Controlling the keyboard
Use pynput.keyboard.Controller to press and release keys programmatically.
Listening to keyboard events
Instantiate pynput.keyboard.Listener with callbacks for key press and release; it also runs in its own thread. Stopping works the same way as the mouse listener. The callback receives a pynput.keyboard.Key instance for special keys and a pynput.keyboard.KeyCode instance for alphanumeric keys; unknown keys yield None.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
