Fundamentals 3 min read

Using the pynput Library to Control and Monitor Mouse and Keyboard in Python

This article introduces the Python pynput library, explains its mouse and keyboard sub‑packages, demonstrates how to control and monitor mouse movements and clicks as well as keyboard inputs, and details listener behavior, threading, and stopping mechanisms for event monitoring.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Using the pynput Library to Control and Monitor Mouse and Keyboard in Python

The pynput library enables control and monitoring of input devices such as the mouse and keyboard from Python code.

It provides two main sub‑packages: pynput.mouse , which contains classes for controlling and observing mouse or touchpad actions, and pynput.keyboard , which contains classes for controlling and observing keyboard activity.

Both sub‑packages are imported directly from pynput , e.g., from pynput import mouse, keyboard .

To control the mouse, you can create a mouse.Controller instance and use its methods to move the cursor, click buttons, or scroll.

To monitor mouse events, instantiate a mouse.Listener . The listener runs in a separate thread, invoking callback functions for events such as move, click, and scroll. The listener stops when Listener.stop() is called, a StopException is raised, or a callback returns False .

Keyboard control is achieved with keyboard.Controller , allowing you to press and release keys programmatically.

Keyboard event monitoring uses keyboard.Listener , which also operates in its own thread. Stopping the listener follows the same rules as the mouse listener. The callback receives a key argument that is either a keyboard.Key instance for special keys or a keyboard.KeyCode instance for alphanumeric keys; unknown keys may be None .

Overall, pynput provides a straightforward API for automating and observing input device interactions in Python.

Pythonautomationkeyboardinput-devicespynputmouse
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.