pynput Documentation
repository·master·Indexed 24 days ago
https://github.com/moses-palmer/pynputA library for controlling and monitoring input devices, specifically supporting mouse and keyboard input. It provides Controller classes to simulate input and Listener classes to monitor events across multiple platforms, including macOS, Windows, and Linux (Xorg, uinput, and Wayland). Features include global hotkey registration, synchronous event polling via the Events class, and platform-specific event suppression.
What's inside pynput
- pynput is a Python library designed to control and monitor input devices. It provides interfaces for both mouse and keyboard input, allowing you to programmatically simulate user actions or listen to device events.
Control and monitor the keyboard with pynput.keyboard
masterThepynput.keyboardmodule provides tools to both simulate keyboard input (controlling) and intercept keyboard events (monitoring/listening).Control and monitor the mouse with pynput.mouse
masterThe
pynput.mousemodule provides tools to both control the mouse (simulating movement and clicks) and monitor it (listening to mouse events).To control the mouse, use the
pynput.mouse.Controllerclass. To monitor mouse activity, use thepynput.mouse.Listenerclass.Configure pynput for Linux (Wayland)
masterOn Wayland-based systems,pynputtypically relies on theXwaylandemulator. This results in limited functionality: you will only receive input events from applications that are also running under theXwaylandemulator.How HotKey works for custom state management
masterThe
pynput.keyboard.HotKeyclass is a lower-level abstraction used to manage the state of a multi-key combination. Because aListeneris stateless, you must useHotKey.pressandHotKey.releasewithin your listener callbacks to track which keys are currently held down.To ensure compatibility, keys should be passed through
Listener.canonical()before being sent to theHotKeyinstance to normalize modifiers.from pynput import keyboard def on_activate(): print('Global hotkey activated!') def for_canonical(f): return lambda k: f(l.canonical(k)) hotkey = keyboard.HotKey( keyboard.HotKey.parse('<ctrl>+<alt>+h'), on_activate) with keyboard.Listener( on_press=for_canonical(hotkey.press), on_release=for_canonical(hotkey.release)) as l: l.join()Import pynput subpackages
masterTo control or monitor input devices, import the
mouseorkeyboardsubpackages directly from the mainpynputpackage. All device-specific modules are automatically imported into the top-level package.from pynput import mouse, keyboardHandle errors in mouse listener callbacks
masterIf a callback handler raises an exception, the listener will stop. Because callbacks run in a dedicated thread, exceptions are not automatically reraised in your main thread.
To catch exceptions raised within a callback, you must call
listener.join()within atry...exceptblock in your main thread.from pynput import mouse class MyException(Exception): pass def on_click(x, y, button, pressed): if button == mouse.Button.left: raise MyException(button) with mouse.Listener(on_click=on_click) as listener: try: listener.join() except MyException as e: print(f'Caught exception from callback: {e.args[0]}')Monitor mouse events with Listener
masterUse
pynput.mouse.Listenerto monitor mouse activity. The listener runs in a dedicatedthreading.Thread.Callback Signatures
on_move(x, y, injected)on_click(x, y, button, pressed, injected)on_scroll(x, y, dx, dy, injected)
Note:
injectedis a boolean indicating if the event was generated by a controller rather than a physical device.Usage Modes
- Blocking: Use a
withstatement and calllistener.join(). This blocks the current thread until the listener stops. - Non-blocking: Call
listener.start(). This allows the current thread to continue executing. This is useful for GUI integration but will cause a standalone script to exit immediately if not managed.
Stopping the Listener
To stop the listener, you can:
- Return
Falsefrom any callback function. - Call
pynput.mouse.Listener.stop()from anywhere. - Raise
StopExceptionfrom a callback.
Configure pynput for Linux (X11)
masterWhen running on Linux using the X server, ensure that an X server is active and the
$DISPLAYenvironment variable is correctly set. If running over SSH, you must manually set the$DISPLAYvariable to point to the local X session to allowpynputto interface with the display.To find your current
$DISPLAYvalue, runecho $DISPLAYin a terminal within your desktop environment.$ DISPLAY=:0 python -c 'import pynput'Configure pynput for macOS (Keyboard Permissions)
masterRecent versions of macOS restrict keyboard monitoring for security. To monitor the keyboard, you must satisfy one of the following:
- Run the process as root.
- Whitelist your application under Enable access for assistive devices in System Settings. (Note: If running as a script, you may need to whitelist your entire Python installation or package your application).
- On macOS versions after Mojave, you may also need to whitelist your terminal application if running the script from a terminal.
Note: These restrictions do not apply to monitoring the mouse or trackpad.
Suppress specific events on Windows
masterOn Windows, you can suppress specific events by passing a
win32_event_filtercallable to the listener constructor. This function receives(msg, data), wheredatais aMSLLHOOKSTRUCT(for mouse) or aKBDLLHOOKSTRUCT(for keyboard).To suppress the event, call
listener.suppress_event()within the filter function. ReturningFalsefrom the filter function will also hide the event from other listener callbacks.# Values for MSLLHOOKSTRUCT.vkCode can be found here: # https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes def win32_event_filter(msg, data): if data.vkCode == 0x58: # Suppress x listener.suppress_event() # Use it in the listener constructor # listener = keyboard.Listener(win32_event_filter=win32_event_filter)Suppress specific events on macOS
masterOn macOS, you can suppress specific events by passing a
darwin_interceptcallable to the listener constructor. This function receives(event_type, event), whereeventis aCGEventRef.To suppress an event, return
None. To allow the event (or a modified version of it) to pass through, return theeventobject. You can use theQuartzmodule to inspect or modify the event.def darwin_intercept(event_type, event): import Quartz length, chars = Quartz.CGEventKeyboardGetUnicodeString( event, 100, None, None) if length > 0 and chars == 'x': # Suppress x return None elif length > 0 and chars == 'a': # Transform a to b Quartz.CGEventKeyboardSetUnicodeString(event, 1, 'b') else: return event # Use it in the listener constructor # listener = keyboard.Listener(darwin_intercept=darwin_intercept)