### pynput.keyboard.Listener.start() Source: https://pynput.readthedocs.io/en/latest/genindex.html Starts the keyboard listener. This method is part of the pynput.keyboard.Listener class. ```APIDOC ## pynput.keyboard.Listener.start() ### Description Starts the keyboard listener. ### Method start ### Class pynput.keyboard.Listener ``` -------------------------------- ### pynput.mouse.Listener.start() Source: https://pynput.readthedocs.io/en/latest/genindex.html Starts the mouse listener. This method is part of the pynput.mouse.Listener class. ```APIDOC ## pynput.mouse.Listener.start() ### Description Starts the mouse listener. ### Method start ### Class pynput.mouse.Listener ``` -------------------------------- ### Thread _bootstrap_inner method Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Performs the internal setup for a new thread, including setting identifiers, locks, and trace/profile hooks. ```python def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) ``` -------------------------------- ### Thread start method Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Starts the thread's activity by invoking the run() method in a separate thread. Raises RuntimeError if called more than once. ```python def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError("thread.__init__() not called") if self._started.is_set(): raise RuntimeError("threads can only be started once") with _active_limbo_lock: _limbo[self] = self try: _start_new_thread(self._bootstrap, ()) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait() ``` -------------------------------- ### Threading Module Initialization Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Initial setup of the threading module, including imports and the definition of the public API. ```python """Thread module emulating a subset of Java's threading model.""" import os as _os import sys as _sys import _thread from time import monotonic as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice, count as _count try: from _collections import deque as _deque except ImportError: from collections import deque as _deque # Note regarding PEP 8 compliant names # This threading model was originally inspired by Java, and inherited # the convention of camelCase function and method names from that # language. Those original names are not in any imminent danger of # being deprecated (even for Py3k),so this module provides them as an # alias for the PEP 8 compliant names # Note that using the new PEP 8 compliant names facilitates substitution # with the multiprocessing module, which doesn't provide the old # Java inspired names. __all__ = ['get_ident', 'active_count', 'Condition', 'current_thread', 'enumerate', 'main_thread', 'TIMEOUT_MAX', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'] # Rename some stuff so "from threading import *" is safe _start_new_thread = _thread.start_new_thread _allocate_lock = _thread.allocate_lock _set_sentinel = _thread._set_sentinel get_ident = _thread.get_ident ThreadError = _thread.error try: _CRLock = _thread.RLock except AttributeError: _CRLock = None TIMEOUT_MAX = _thread.TIMEOUT_MAX del _thread ``` -------------------------------- ### Timer class usage Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Example of using the Timer class to execute a function after a delay. ```python t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting ``` -------------------------------- ### AbstractListener context manager methods Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/_util.html Enables the use of the listener with the 'with' statement to automatically start and stop the listener. ```python def __enter__(self): self.start() self.wait() return self def __exit__(self, exc_type, value, traceback): self.stop() ``` -------------------------------- ### Listener context manager equivalent code Source: https://pynput.readthedocs.io/en/latest/mouse.html Shows the equivalent code for using a Listener as a context manager: start the listener, wait, execute the with-statements, and stop the listener in a finally block. ```python listener.start() try: listener.wait() with_statements() finally: listener.stop() ``` -------------------------------- ### Listener.start() Source: https://pynput.readthedocs.io/en/latest/mouse.html Starts the listener thread's activity. It must be called at most once per listener instance and arranges for the run() method to be invoked in a separate thread. Raises RuntimeError if called more than once. ```APIDOC ## Listener.start() ### Description Starts the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. ### Method start ### Parameters None ### Return Value None ### Exceptions - RuntimeError - If called more than once on the same thread object. ``` -------------------------------- ### pynput.keyboard.Listener.start Source: https://pynput.readthedocs.io/en/latest/keyboard.html Starts the thread's activity. It arranges for the object's run() method to be invoked in a separate thread of control. ```APIDOC ## pynput.keyboard.Listener.start ### Description Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. ### Raises - **RuntimeError** - If called more than once on the same thread object. ``` -------------------------------- ### pynput.keyboard.Listener Source: https://pynput.readthedocs.io/en/latest/_sources/keyboard.rst.txt The Listener class monitors keyboard events and allows starting and stopping the listener. ```APIDOC ## pynput.keyboard.Listener ### Description Listener for keyboard events. Can be started and stopped, and provides a running property. ### Methods - **start()** - Start the listener. - **stop()** - Stop the listener. - **wait()** - Wait for the listener to finish. ### Properties - **running** (bool) - Whether the listener is currently running. ### Usage Example ```python from pynput.keyboard import Listener listener = Listener() listener.start() # ... listener.stop() ``` ``` -------------------------------- ### Basic mouse listener with on_move, on_click, on_scroll Source: https://pynput.readthedocs.io/en/latest/mouse.html Creates a pynput.mouse.Listener that prints pointer movement, click press/release, and scroll events. The blocking version uses a context manager and join(), while the non-blocking version calls start() and lets the current thread continue. Returning False from on_click stops the listener. ```python from pynput import mouse def on_move(x, y): print('Pointer moved to {0}'.format( (x, y))) def on_click(x, y, button, pressed): print('{0} at {1}'.format( 'Pressed' if pressed else 'Released', (x, y))) if not pressed: # Stop listener return False def on_scroll(x, y, dx, dy): print('Scrolled {0} at {1}'.format( 'down' if dy < 0 else 'up', (x, y))) # Collect events until released with mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() # ...or, in a non-blocking fashion: listener = mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) listener.start() ``` -------------------------------- ### pynput._util.AbstractListener.run() Source: https://pynput.readthedocs.io/en/latest/genindex.html Runs the listener loop. This method is part of the abstract listener class and is used to start listening for events. ```APIDOC ## pynput._util.AbstractListener.run() ### Description Runs the listener loop. This method is part of the abstract listener class and is used to start listening for events. ### Method run ### Parameters None ### Returns None ``` -------------------------------- ### Listener class Source: https://pynput.readthedocs.io/en/latest/keyboard.html A listener for keyboard events. Instances can be used as context managers, equivalent to start(), wait(), and stop() in a try/finally block. ```APIDOC ## Listener(on_press=None, on_release=None, suppress=False, **kwargs) ### Description A listener for keyboard events. Instances of this class can be used as context managers. This is equivalent to the following code: listener.start() try: listener.wait() with_statements() finally: listener.stop() ### Parameters - **on_press** - Callback for press events. - **on_release** - Callback for release events. - **suppress** - Whether to suppress events. - **kwargs** - Additional keyword arguments. ``` -------------------------------- ### Events class initialization and lifecycle Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/_util.html The Events class manages an event queue and listener lifecycle. It implements context manager methods for automatic setup and teardown. ```python def __init__(self, *args, **kwargs): super(Events, self).__init__() self._event_queue = queue.Queue() self._sentinel = object() self._listener = self._Listener(*args, **{ key: self._event_mapper(value) for (key, value) in kwargs.items()}) self.start = self._listener.start def __enter__(self): self._listener.__enter__() return self def __exit__(self, *args): self._listener.__exit__(*args) # Drain the queue to ensure that the put does not block while True: try: self._event_queue.get_nowait() except queue.Empty: break self._event_queue.put(self._sentinel) def __iter__(self): return self def __next__(self): event = self.get() if event is not None: return event else: raise StopIteration() ``` -------------------------------- ### Thread join method implementation Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Handles blocking until a thread terminates, including error checks for initialization, start status, and deadlock prevention. ```python if not self._initialized: raise RuntimeError("Thread.__init__() not called") if not self._started.is_set(): raise RuntimeError("cannot join thread before it is started") if self is current_thread(): raise RuntimeError("cannot join current thread") if timeout is None: self._wait_for_tstate_lock() else: # the behavior of a negative timeout isn't documented, but # historically .join(timeout=x) for x<0 has acted as if timeout=0 self._wait_for_tstate_lock(timeout=max(timeout, 0)) ``` -------------------------------- ### Listener.__init__ Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Initializes a keyboard listener with callbacks for key press and release events, and options for event suppression and platform-specific configuration. ```APIDOC ## Listener.__init__ ### Description Initializes a keyboard listener. The listener can be used as a context manager, equivalent to calling start(), wait(), and stop(). It inherits from threading.Thread and sets daemon to True. ### Method Constructor ### Signature Listener(on_press=None, on_release=None, suppress=False, **kwargs) ### Parameters - **on_press** (callable) - Optional - The callback to call when a button is pressed. It will be called with the argument (key), where key is a KeyCode, a Key, or None if the key is unknown. - **on_release** (callable) - Optional - The callback to call when a button is released. It will be called with the argument (key), where key is a KeyCode, a Key, or None if the key is unknown. - **suppress** (bool) - Optional - Whether to suppress events. Setting this to True will prevent the input events from being passed to the rest of the system. - **kwargs** - Optional - Any non-standard platform dependent options. These should be prefixed with the platform name: darwin_, uinput_, xorg_, or win32_. Supported values include: - darwin_intercept: A callable taking the arguments (event_type, event), where event_type is Quartz.kCGEventKeyDown or Quartz.kCGEventKeyUp, and event is a CGEventRef. This callable can freely modify the event. If it does not return the event, the event is suppressed system wide. - uinput_device_paths: A list of device paths. If specified, pynput will limit the number of devices checked for the capabilities needed to those passed, otherwise all system devices will be used. - win32_event_filter: A callable taking the arguments (msg, data), where msg is the current message, and data is associated data as a KBDLLHOOKSTRUCT. If this callback returns False, the event will not be propagated to the listener callback. If self.suppress_event() is called, the event is suppressed system wide. ### Usage Example listener = Listener(on_press=on_press, on_release=on_release, suppress=False) listener.start() try: listener.wait() with_statements() finally: listener.stop() ``` -------------------------------- ### pynput.mouse.Listener Source: https://pynput.readthedocs.io/en/latest/_sources/mouse.rst.txt The Listener class monitors mouse events and allows starting and stopping the monitoring thread. It provides methods to start, stop, and wait for the listener. ```APIDOC ## pynput.mouse.Listener ### Description Monitors mouse events and provides methods to start, stop, and wait for the listener. ### Constructor - **__init__(on_move=None, on_click=None, on_scroll=None)** - Initialize the listener with optional callbacks for mouse events. ### Properties - **running** - Whether the listener is currently running. ### Methods - **start()** - Start the listener thread. - **stop()** - Stop the listener thread. - **wait()** - Wait for the listener to finish. ``` -------------------------------- ### Control the mouse with pynput.mouse.Controller Source: https://pynput.readthedocs.io/en/latest/mouse.html Demonstrates how to instantiate the mouse controller to read and set the pointer position, perform relative movements, simulate button presses, clicks, and scrolling. ```python from pynput.mouse import Button, Controller mouse = Controller() # Read pointer position print('The current pointer position is {0}'.format( mouse.position)) # Set pointer position mouse.position = (10, 20) print('Now we have moved it to {0}'.format( mouse.position)) # Move pointer relative to current position mouse.move(5, -5) # Press and release mouse.press(Button.left) mouse.release(Button.left) # Double click; this is different from pressing and releasing # twice on macOS mouse.click(Button.left, 2) # Scroll two steps down mouse.scroll(0, 2) ``` -------------------------------- ### Controller.tap Method Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Simulates a full key press and release cycle. ```python def tap(self, key): """Presses and releases a key. This is equivalent to the following code:: controller.press(key) controller.release(key) :param key: The key to press. :raises InvalidKeyException: if the key is invalid :raises ValueError: if ``key`` is a string, but its length is not ``1`` """ self.press(key) self.release(key) ``` -------------------------------- ### Thread identifier property Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Returns the nonzero integer identifier of the thread, or None if not started. ```python @property def ident(self): """Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. """ assert self._initialized, "Thread.__init__() not called" return self._ident ``` -------------------------------- ### pynput.keyboard.Listener.__init__ Source: https://pynput.readthedocs.io/en/latest/keyboard.html Constructor for the Listener class. Should be called with keyword arguments. Accepts callbacks for key press and release events, a suppress flag, and platform-specific options. ```APIDOC ## pynput.keyboard.Listener.__init__ ### Description Initializes a new keyboard listener. This constructor should always be called with keyword arguments. It sets the daemon attribute to True. ### Parameters - **on_press** (callable) - Optional - The callback to call when a button is pressed. It will be called with the argument (key), where key is a KeyCode, a Key, or None if the key is unknown. - **on_release** (callable) - Optional - The callback to call when a button is released. It will be called with the argument (key), where key is a KeyCode, a Key, or None if the key is unknown. - **suppress** (bool) - Optional - Whether to suppress events. Setting this to True will prevent the input events from being passed to the rest of the system. - **kwargs** - Optional - Any non-standard platform dependent options. These should be prefixed with the platform name: darwin_, uinput_, xorg_, or win32_. Supported values include: - **darwin_intercept** (callable) - A callable taking the arguments (event_type, event), where event_type is Quartz.kCGEventKeyDown or Quartz.kCGEventKeyUp, and event is a CGEventRef. This callable can freely modify the event. If it does not return the event, the event is suppressed system wide. - **uinput_device_paths** (list) - A list of device paths. If specified, pynput will limit the number of devices checked for capabilities to those passed. Passing this might be required if an incorrect device is chosen. - **win32_event_filter** (callable) - A callable taking the arguments (msg, data), where msg is the current message, and data is associated data as a KBDLLHOOKSTRUCT. If this callback returns False, the event will not be propagated to the listener callback. If self.suppress_event() is called, the event is suppressed system wide. ### Notes - The constructor also accepts standard threading.Thread arguments: group, target, name, args, and kwargs. group should be None; target is the callable object to be invoked by run(); name is the thread name; args is the argument tuple for the target invocation; kwargs is a dictionary of keyword arguments for the target invocation. - If a subclass overrides the constructor, it must invoke the base class constructor (Thread.__init__()) before doing anything else. ``` -------------------------------- ### Control the keyboard with pynput.keyboard.Controller Source: https://pynput.readthedocs.io/en/latest/keyboard.html Demonstrates how to press, release, and type keys using the Controller class. ```python from pynput.keyboard import Key, Controller keyboard = Controller() # Press and release space keyboard.press(Key.space) keyboard.release(Key.space) # Type a lower case A; this will work even if no key on the # physical keyboard is labelled 'A' keyboard.press('a') keyboard.release('a') # Type two upper case As keyboard.press('A') keyboard.release('A') with keyboard.pressed(Key.shift): keyboard.press('a') keyboard.release('a') # Type 'Hello World' using the shortcut type method keyboard.type('Hello World') ``` -------------------------------- ### Main Thread Accessor Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Returns the main thread object, which is the thread from which the Python interpreter was started. ```python def main_thread(): """Return the main thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. """ return _main_thread ``` -------------------------------- ### Listener.__init__ Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/mouse/_base.html Initializes a new mouse listener with optional callbacks for move, click, and scroll events, and a suppress flag. ```APIDOC ## Listener.__init__ ### Description Initializes a new mouse listener with optional callbacks for move, click, and scroll events, and a suppress flag. ### Method Constructor ### Signature Listener(on_move=None, on_click=None, on_scroll=None, suppress=False, **kwargs) ### Parameters - **on_move** (callable) - Optional - Callback for mouse move events. Called with (x, y). If raises StopException or returns False, listener stops. - **on_click** (callable) - Optional - Callback for mouse click events. Called with (x, y, button, pressed). If raises StopException or returns False, listener stops. - **on_scroll** (callable) - Optional - Callback for mouse scroll events. Called with (x, y, dx, dy). If raises StopException or returns False, listener stops. - **suppress** (bool) - Optional - Whether to suppress events system-wide. - **kwargs** - Optional - Platform-specific options prefixed with platform name (e.g., darwin_, xorg_, win32_). Supported values: darwin_intercept, win32_event_filter. ### Notes - The Listener class inherits from threading.Thread and can be used as a context manager. - When used as a context manager, it starts the listener, waits, and stops it. - The daemon attribute is set to True when created. ``` -------------------------------- ### Thread daemon property accessors Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Manages the daemon status of a thread. Must be set before start() is called. ```python @property def daemon(self): """A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when only daemon threads are left. """ assert self._initialized, "Thread.__init__() not called" return self._daemonic @daemon.setter def daemon(self, daemonic): if not self._initialized: raise RuntimeError("Thread.__init__() not called") if self._started.is_set(): raise RuntimeError("cannot set daemon status of active thread") self._daemonic = daemonic ``` -------------------------------- ### Monitor keyboard events with pynput.keyboard.Listener Source: https://pynput.readthedocs.io/en/latest/keyboard.html Shows how to set up blocking and non-blocking keyboard listeners to capture press and release events. ```python from pynput import keyboard def on_press(key): try: print('alphanumeric key {0} pressed'.format( key.char)) except AttributeError: print('special key {0} pressed'.format( key)) def on_release(key): print('{0} released'.format( key)) if key == keyboard.Key.esc: # Stop listener return False # Collect events until released with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: listener.join() # ...or, in a non-blocking fashion: listener = keyboard.Listener( on_press=on_press, on_release=on_release) listener.start() ``` -------------------------------- ### Controller.scroll(dx, dy) Source: https://pynput.readthedocs.io/en/latest/mouse.html Sends scroll events. Raises ValueError if the values are invalid, for example out of bounds. ```APIDOC ## Controller.scroll(dx, dy) ### Description Sends scroll events. Raises ValueError if the values are invalid, for example out of bounds. ### Method scroll ### Parameters - **dx** (int) - Required - The horizontal scroll. The units of scrolling is undefined. - **dy** (int) - Required - The vertical scroll. The units of scrolling is undefined. ### Raises - **ValueError** - if the values are invalid, for example out of bounds. ### Returns None ``` -------------------------------- ### AbstractListener context manager usage Source: https://pynput.readthedocs.io/en/latest/private.html Demonstrates the equivalent behavior of using an AbstractListener instance as a context manager. ```python listener.start() listener.wait() try: with_statements() finally: listener.stop() ``` -------------------------------- ### Listener Initialization Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html The constructor for the keyboard listener, handling callbacks, event suppression, and platform-specific keyword arguments. ```python def __init__(self, on_press=None, on_release=None, suppress=False, **kwargs): self._log = _logger(self.__class__) option_prefix = prefix(Listener, self.__class__) self._options = { key[len(option_prefix):]: value for key, value in kwargs.items() if key.startswith(option_prefix)} super(Listener, self).__init__( on_press=on_press, on_release=on_release, suppress=suppress) ``` -------------------------------- ### Controller.release Method Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Simulates releasing a key. ```python def release(self, key): """Releases a key. A key may be either a string of length 1, one of the :class:`Key` members or a :class:`KeyCode`. Strings will be transformed to :class:`KeyCode` using :meth:`KeyCode.char`. Members of :class:`Key` will be translated to their :meth:`~Key.value`. :param key: The key to release. If this is a string, it is passed to :meth:`touches` and the returned releases are used. :raises InvalidKeyException: if the key is invalid :raises ValueError: if ``key`` is a string, but its length is not ``1`` """ resolved = self._resolve(key) if resolved is None: raise self.InvalidKeyException(key) self._update_modifiers(resolved, False) # Ignore released dead keys if resolved.is_dead: return self._handle(resolved, False) ``` -------------------------------- ### Controller.position Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/mouse/_base.html Gets or sets the current position of the mouse pointer as a tuple (x, y). Setting this property moves the pointer. ```APIDOC ## Controller.position ### Description Gets or sets the current position of the mouse pointer. The position is a tuple (x, y). Setting this property moves the pointer. ### Property - **type**: tuple (x, y) - **getter**: Returns the current position - **setter**: Moves the pointer to the given position ``` -------------------------------- ### Register multiple global hotkeys with GlobalHotKeys Source: https://pynput.readthedocs.io/en/latest/keyboard.html Uses the GlobalHotKeys convenience class to register multiple shortcut strings and their corresponding activation callbacks. ```python from pynput import keyboard def on_activate_h(): print('++h pressed') def on_activate_i(): print('++i pressed') with keyboard.GlobalHotKeys({ '++h': on_activate_h, '++i': on_activate_i}) as h: h.join() ``` -------------------------------- ### Controller.press Method Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Simulates pressing a key, handling modifiers, caps lock state, and dead keys. ```python def press(self, key): """Presses a key. A key may be either a string of length 1, one of the :class:`Key` members or a :class:`KeyCode`. Strings will be transformed to :class:`KeyCode` using :meth:`KeyCode.char`. Members of :class:`Key` will be translated to their :meth:`~Key.value`. :param key: The key to press. :raises InvalidKeyException: if the key is invalid :raises ValueError: if ``key`` is a string, but its length is not ``1`` """ resolved = self._resolve(key) if resolved is None: raise self.InvalidKeyException(key) self._update_modifiers(resolved, True) # Update caps lock state if resolved == self._Key.caps_lock.value: self._caps_lock = not self._caps_lock # If we currently have a dead key pressed, join it with this key original = resolved if self._dead_key: try: resolved = self._dead_key.join(resolved) except ValueError: self._handle(self._dead_key, True) self._handle(self._dead_key, False) # If the key is a dead key, keep it for later if resolved.is_dead: self._dead_key = resolved return try: self._handle(resolved, True) except self.InvalidKeyException: if resolved != original: self._handle(self._dead_key, True) self._handle(self._dead_key, False) self._handle(original, True) self._dead_key = None ``` -------------------------------- ### KeyCode.join Source: https://pynput.readthedocs.io/en/latest/keyboard.html Instance method that applies this dead key to another key and returns the result. Joining with space or itself yields the non-dead version if one exists. ```APIDOC ## KeyCode.join ### Description Applies this dead key to another key and returns the result. ### Method instance ### Parameters - **key** (KeyCode) - Required - The key to join with this key. ### Returns - a key code ### Raises - **ValueError** - if the keys cannot be joined ``` -------------------------------- ### pynput.keyboard.KeyCode.from_vk() Source: https://pynput.readthedocs.io/en/latest/genindex.html Class method to create a KeyCode from a virtual key code. ```APIDOC ## pynput.keyboard.KeyCode.from_vk() ### Description Class method to create a KeyCode from a virtual key code. ### Method from_vk ### Class pynput.keyboard.KeyCode ``` -------------------------------- ### Reading a single mouse event with pynput.mouse.Events Source: https://pynput.readthedocs.io/en/latest/mouse.html Uses pynput.mouse.Events to read a single mouse event in a non-blocking way. The get(1.0) call blocks for at most one second and returns None if no event occurs, printing a message accordingly. ```python from pynput import mouse # The event listener will be running in this block with mouse.Events() as events: # Block at most one second event = events.get(1.0) if event is None: print('You did not interact with the mouse within one second') else: print('Received event {}'.format(event)) ``` -------------------------------- ### KeyCode.join Method Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Applies a dead key to another key to produce a combined character. ```python def join(self, key): """Applies this dead key to another key and returns the result. Joining a dead key with space (``' '``) or itself yields the non-dead version of this key, if one exists; for example, ``KeyCode.from_dead('~').join(KeyCode.from_char(' '))`` equals ``KeyCode.from_char('~')`` and ``KeyCode.from_dead('~').join(KeyCode.from_dead('~'))``. :param KeyCode key: The key to join with this key. :return: a key code :raises ValueError: if the keys cannot be joined """ # A non-dead key cannot be joined if not self.is_dead: raise ValueError(self) # Joining two of the same keycodes, or joining with space, yields the # non-dead version of the key if key.char == ' ' or self == key: return self.from_char(self.char) # Otherwise we combine the characters if key.char is not None: combined = unicodedata.normalize( 'NFC', key.char + self.combining) if combined: return self.from_char(combined) raise ValueError(key) ``` -------------------------------- ### Handling mouse listener errors with custom exception Source: https://pynput.readthedocs.io/en/latest/mouse.html Shows how to catch exceptions raised in a mouse listener callback. The listener stops when a callback raises an exception, and the exception is re-raised when join() is called. This example raises MyException when the left button is clicked. ```python from pynput import mouse class MyException(Exception): pass def on_click(x, y, button, pressed): if button == mouse.Button.left: raise MyException(button) # Collect events until released with mouse.Listener( on_click=on_click) as listener: try: listener.join() except MyException as e: print('{0} was clicked'.format(e.args[0])) ``` -------------------------------- ### Listener.running Source: https://pynput.readthedocs.io/en/latest/mouse.html Whether the listener is currently running. ```APIDOC ## Listener.running ### Description Whether the listener is currently running. ### Property running ### Returns bool - True if the listener is currently running, False otherwise. ``` -------------------------------- ### Handle keyboard listener errors Source: https://pynput.readthedocs.io/en/latest/keyboard.html Demonstrates how to catch exceptions raised within a listener callback by joining the listener thread. ```python from pynput import keyboard class MyException(Exception): pass def on_press(key): if key == keyboard.Key.esc: raise MyException(key) # Collect events until released with keyboard.Listener( on_press=on_press) as listener: try: listener.join() except MyException as e: print('{0} was pressed'.format(e.args[0])) ``` -------------------------------- ### Legacy thread methods Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Compatibility methods for daemon status and naming. ```python def isDaemon(self): return self.daemon def setDaemon(self, daemonic): self.daemon = daemonic def getName(self): return self.name def setName(self, name): self.name = name ``` -------------------------------- ### pynput.keyboard.KeyCode.from_dead() Source: https://pynput.readthedocs.io/en/latest/genindex.html Class method to create a KeyCode from a dead key. ```APIDOC ## pynput.keyboard.KeyCode.from_dead() ### Description Class method to create a KeyCode from a dead key. ### Method from_dead ### Class pynput.keyboard.KeyCode ``` -------------------------------- ### Equivalent implementation of controller.tap Source: https://pynput.readthedocs.io/en/latest/keyboard.html The tap method is a convenience wrapper that performs a press and release sequence. ```python controller.press(key) controller.release(key) ``` -------------------------------- ### KeyCode Factory Methods Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Factory methods to create KeyCode instances from virtual key codes, characters, or dead keys. ```python @classmethod def from_vk(cls, vk, **kwargs): """Creates a key from a virtual key code. :param vk: The virtual key code. :param kwargs: Any other parameters to pass. :return: a key code """ return cls(vk=vk, **kwargs) @classmethod def from_char(cls, char, **kwargs): """Creates a key from a character. :param str char: The character. :return: a key code """ return cls(char=char, **kwargs) @classmethod def from_dead(cls, char, **kwargs): """Creates a dead key. :param char: The dead key. This should be the unicode character representing the stand alone character, such as ``'~'`` for *COMBINING TILDE*. :return: a key code """ return cls(char=char, is_dead=True, **kwargs) ``` -------------------------------- ### Controller.press(key) Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Presses a key. The key can be a string of length 1, a Key member, or a KeyCode. Raises InvalidKeyException for invalid keys and ValueError for strings not of length 1. ```APIDOC ## Controller.press(key) ### Description Presses a key. A key may be either a string of length 1, one of the Key members or a KeyCode. Strings will be transformed to KeyCode using KeyCode.char. Members of Key will be translated to their Key.value. ### Method press ### Parameters - **key** (str, Key, or KeyCode) - Required - The key to press. ### Exceptions - **InvalidKeyException** - if the key is invalid - **ValueError** - if key is a string, but its length is not 1 ``` -------------------------------- ### Timer Thread Initialization and Execution Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Defines the initialization and run logic for a timer-based thread, including the cancel method to stop the timer. ```python def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() ``` -------------------------------- ### pynput.keyboard.Controller.touch() Source: https://pynput.readthedocs.io/en/latest/genindex.html Simulates touching a key on the keyboard. This method is part of the pynput.keyboard.Controller class. ```APIDOC ## pynput.keyboard.Controller.touch() ### Description Simulates touching a key on the keyboard. ### Method touch ### Class pynput.keyboard.Controller ``` -------------------------------- ### Condition.notify and notify_all implementation Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Wakes up waiting threads. notify_all is an alias for notify_all. ```python def notify(self, n=1): """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting. """ if not self._is_owned(): raise RuntimeError("cannot notify on un-acquired lock") all_waiters = self._waiters waiters_to_notify = _deque(_islice(all_waiters, n)) if not waiters_to_notify: return for waiter in waiters_to_notify: waiter.release() try: all_waiters.remove(waiter) except ValueError: pass def notify_all(self): """Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. """ self.notify(len(self._waiters)) notifyAll = notify_all ``` -------------------------------- ### AbstractListener _mark_ready method Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/_util.html Signals that the listener is ready to receive events, unblocking the wait method. ```python def _mark_ready(self): """Marks this listener as ready to receive events. This method must be called from :meth:`_run`. :meth:`wait` will block until this method is called. """ self._condition.acquire() self._ready = True self._condition.notify() self._condition.release() ``` -------------------------------- ### Thread-Local Implementation Import Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Attempts to import the thread-local implementation from the _thread module, falling back to _threading_local if unavailable. ```python try: from _thread import _local as local except ImportError: from _threading_local import local ``` -------------------------------- ### pynput.keyboard.KeyCode.from_char() Source: https://pynput.readthedocs.io/en/latest/genindex.html Class method to create a KeyCode from a character. ```APIDOC ## pynput.keyboard.KeyCode.from_char() ### Description Class method to create a KeyCode from a character. ### Method from_char ### Class pynput.keyboard.KeyCode ``` -------------------------------- ### NotifierMixin listener management methods Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/_util.html Methods for iterating, adding, and removing listeners from the internal cache. ```python @classmethod def _listeners(cls): """Iterates over the set of running listeners. This method will quit without acquiring the lock if the set is empty, so there is potential for race conditions. This is an optimisation, since :class:`Controller` will need to call this method for every control event. """ if not cls._listener_cache: return with cls._listener_lock: for listener in cls._listener_cache: yield listener @classmethod def _add_listener(cls, listener): """Adds a listener to the set of running listeners. :param listener: The listener for fake events. """ with cls._listener_lock: cls._listener_cache.add(listener) @classmethod def _remove_listener(cls, listener): """Removes this listener from the set of running listeners. ``` -------------------------------- ### Controller.tap(key) Source: https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html Presses and releases a key. Equivalent to calling press(key) followed by release(key). ```APIDOC ## Controller.tap(key) ### Description Presses and releases a key. This is equivalent to the following code: controller.press(key); controller.release(key). ### Method tap ### Parameters - **key** (str, Key, or KeyCode) - Required - The key to press. ### Exceptions - **InvalidKeyException** - if the key is invalid - **ValueError** - if key is a string, but its length is not 1 ``` -------------------------------- ### Enabling DPI awareness on Windows for consistent coordinates Source: https://pynput.readthedocs.io/en/latest/mouse.html Sets the process DPI awareness to PROCESS_PER_MONITOR_DPI_AWARE using ctypes.windll.shcore.SetProcessDpiAwareness. This is a process-global setting that must be run before using the mouse listener and controller to ensure consistent coordinates on Windows. ```python import ctypes PROCESS_PER_MONITOR_DPI_AWARE = 2 ctypes.windll.shcore.SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE) ``` -------------------------------- ### Listener(on_move=None, on_click=None, on_scroll=None, suppress=False, **kwargs) Source: https://pynput.readthedocs.io/en/latest/mouse.html A listener for mouse events. Instances can be used as context managers. Inherits from threading.Thread and supports all its methods. It will set daemon to True when created. ```APIDOC ## Listener(on_move=None, on_click=None, on_scroll=None, suppress=False, **kwargs) ### Description A listener for mouse events. Instances can be used as context managers. Inherits from threading.Thread and supports all its methods. It will set daemon to True when created. ### Constructor Parameters - **on_move** (callable) - Optional - The callback to call when mouse move events occur. It will be called with the arguments (x, y), which is the new pointer position. If this callback raises StopException or returns False, the listener is stopped. - **on_click** (callable) - Optional - The callback to call when a mouse button is clicked. It will be called with the arguments (x, y, button, pressed), where (x, y) is the new pointer position, button is one of the Button values and pressed is whether the button was pressed. If this callback raises StopException or returns False, the listener is stopped. - **on_scroll** (callable) - Optional - The callback to call when mouse scroll events occur. It will be called with the arguments (x, y, dx, dy), where (x, y) is the new pointer position, and (dx, dy) is the scroll vector. If this callback raises StopException or returns False, the listener is stopped. - **suppress** (bool) - Optional - Whether to suppress events. Setting this to True will prevent the input events from being passed to the rest of the system. - **kwargs** - Optional - Any non-standard platform dependent options. These should be prefixed with the platform name thus: darwin_, xorg_ or win32_. Supported values are: - **darwin_intercept** - A callable taking the arguments (event_type, event), where event_type is any mouse related event type constant, and event is a CGEventRef. This callable can freely modify the event using functions like Quartz.CGEventSetIntegerValueField. If this callable does not return the event, the event is suppressed system wide. - **win32_event_filter** - A callable taking the arguments (msg, data), where msg is the current message, and data associated data as a MSLLHOOKSTRUCT. If this callback returns False, the event will not be propagated to the listener callback. If self.suppress_event() is called, the event is suppressed system wide. ### Usage as Context Manager Equivalent to the following code: ``` listener.start() try: listener.wait() with_statements() finally: listener.stop() ``` ``` -------------------------------- ### Controller.press(key) Source: https://pynput.readthedocs.io/en/latest/keyboard.html Presses a key. The key can be a string of length 1, a Key member, or a KeyCode. Raises InvalidKeyException if the key is invalid, or ValueError if the key is a string with length not equal to 1. ```APIDOC ## Controller.press(key) ### Description Presses a key. The key can be a string of length 1, a Key member, or a KeyCode. Strings are transformed to KeyCode using KeyCode.char(). Members of Key are translated to their value(). ### Method press ### Parameters - **key** - The key to press. ### Raises - **InvalidKeyException** - if the key is invalid - **ValueError** - if key is a string, but its length is not 1 ``` -------------------------------- ### Semaphore class initialization Source: https://pynput.readthedocs.io/en/latest/_modules/threading.html Initializes a semaphore with a counter value. ```python class Semaphore: """This class implements semaphore objects. Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ # After Tim Peters' semaphore class, but not quite the same (no maximum) def __init__(self, value=1): if value < 0: raise ValueError("semaphore initial value must be >= 0") self._cond = Condition(Lock()) self._value = value ``` -------------------------------- ### Controller.pressed(*args) Source: https://pynput.readthedocs.io/en/latest/keyboard.html Executes a block with some keys pressed. The keys to keep pressed are passed as arguments. ```APIDOC ## Controller.pressed(*args) ### Description Executes a block with some keys pressed. ### Method pressed ### Parameters - **keys** - The keys to keep pressed. ```