《每日论文》pynput Package Documentation

pynput库提供了一种简单的方式来控制和监听用户的键盘和鼠标输入。它可以用来模拟键盘和鼠标事件,如按下、释放、移动和滚动。此外,还可以创建监听器来实时捕获这些事件,用于自动化任务或游戏控制等。监听器以线程的形式运行,并支持同步和非阻塞两种模式。在Windows系统中,要注意确保处理鼠标和键盘事件时保持系统输入的协调一致。pynput还支持全局热键,可用于创建跨平台的快捷键功能。
摘要由CSDN通过智能技术生成

pynput Package Documentation

This library allows you to control and monitor input devices.
这个库允许你控制和监控输入设备。
It contains subpackages for each type of input device supported:
它包含支持的每种类型输入设备的子包:
pynput.mouse
Contains classes for controlling and monitoring a mouse or trackpad.
包含用于控制和监视鼠标或触控板的类。
pynput.keyboard
Contains classes for controlling and monitoring the keyboard.
包含用于控制和监视键盘的类。

All modules mentioned above are automatically imported into the pynput package. To use any of them, import them from the main package:
上面提到的所有模块都会自动导入到pynput包中。要使用其中任何一个,请从主包中导入它们:

from pynput import mouse, keyboard

Forcing a specific backend

强制指定后端

pynput attempts to use the backend suitable for the current platform, but this automatic choice is possible to override.
pynput尝试使用适合当前平台的后端,但是这种自动选择是可以覆盖的。

If the environment variables $PYNPUT_BACKEND_KEYBOARD or $PYNPUT_BACKEND are set, their value will be used as backend name for the keyboard classes, and if $PYNPUT_BACKEND_MOUSE or $PYNPUT_BACKEND are set, their value will be used as backend name for the mouse classes.
如果设置了环境变量“ $PYNPUT_BACKEND_KEYBOARD”或“ $PYNPUT_BACKEND”,它们的值将被用作键盘类的后端名,如果设置了“ $PYNPUT_BACKEND_MOUSE”或“ $PYNPUT_BACKEND”,它们的值将被用作鼠标类的后端名。

Available backends are:
可用的后端:

  • darwin, the default for macOS. darwin, macOS的默认值。
  • win32, the default for Windows. win32, Windows的默认值。
  • uinput, an optional backend for Linux requiring root privileges and supporting only keyboards. uinput, Linux的可选后端,需要root权限,只支持键盘。
  • xorg, the default for other operating systems. xorg,其他操作系统的默认值。
  • dummy, a non-functional, but importable, backend. This is useful as mouse backend when using the uinput backend. dummy,一个无功能但可导入的后端。当使用uinput后端时,这是非常有用的鼠标后端。

Table of contents

本期目录

Handling the mouse

处理鼠标

The package pynput.mouse contains classes for controlling and monitoring the mouse.
包pynput。包含用于控制和监视鼠标的类。

Controlling the mouse
控制鼠标

Use pynput.mouse.Controller like this:
使用pynput.mouse。控制器是这样的:

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  两次macOS
mouse.click(Button.left, 2)

# Scroll two steps down  向下滚动两步
mouse.scroll(0, 2)
Monitoring the mouse
监视鼠标

Use pynput.mouse.Listener like this:
使用pynput.mouse。侦听器是这样的:

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()

A mouse listener is a threading.Thread, and all callbacks will be invoked from the thread.
鼠标监听器是一个线程。线程,所有的回调函数都将从线程中调用。

Call pynput.mouse.Listener.stop from anywhere, raise StopException or return False from a callback to stop the listener.
从任何地方调用pynput.mouse.Listener.stop,引发StopException或从回调函数中返回False以停止侦听器。

When using the non-blocking version above, the current thread will continue executing. This might be necessary when integrating with other GUI frameworks that incorporate a main-loop, but when run from a script, this will cause the program to terminate immediately.
当使用上面的非阻塞版本时,当前线程将继续执行。当与包含主循环的其他GUI框架集成时,这可能是必要的,但当从脚本运行时,这将导致程序立即终止。

The mouse listener thread
鼠标监听线程

The listener callbacks are invoked directly from an operating thread on some platforms, notably Windows.
监听器回调函数在某些平台上直接从操作线程调用,特别是在Windows上。

This means that long running procedures and blocking operations should not be invoked from the callback, as this risks freezing input for all processes.
这意味着不应该从回调调用长时间运行的过程和阻塞操作,因为这可能会冻结所有进程的输入。

A possible workaround is to just dispatch incoming messages to a queue, and let a separate thread handle them.
一种可能的解决方案是只将传入消息分派到队列,并让单独的线程处理它们。

Handling mouse listener errors
处理鼠标侦听器错误

If a callback handler raises an exception, the listener will be stopped. Since callbacks run in a dedicated thread, the exceptions will not automatically be reraised.
如果回调处理程序引发异常,侦听器将停止。由于回调函数运行在专用线程中,因此异常不会被自动重新引发。

To be notified about callback errors, call Thread.join on the listener instance:
要得到回调错误的通知,请调用Thread.join监听器实例:

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]))
Toggling event listening for the mouse listener
切换鼠标监听器的事件监听

Once pynput.mouse.Listener.stop has been called, the listener cannot be restarted, since listeners are instances of threading.Thread.
一旦pynput.mouse.Listener.stop被调用,则无法重新启动侦听器,因为侦听器是threading.Thread的实例。

If your application requires toggling listening events, you must either add an internal flag to ignore events when not required, or create a new listener when resuming listening.
如果您的应用程序需要切换监听事件,您必须添加一个内部标志来忽略不需要的事件,或者在恢复监听时创建一个新的监听器。

Synchronous event listening for the mouse listener
监听鼠标监听器的同步事件

To simplify scripting, synchronous event listening is supported through the utility class pynput.mouse.Events. This class supports reading single events in a non-blocking fashion, as well as iterating over all events.
为了简化脚本编写,通过实用程序类pynput.mouse.Events支持同步事件监听。该类支持以非阻塞方式读取单个事件,以及遍历所有事件。

To read a single event, use the following code:
要读取单个事件,使用以下代码:

from pynput import mouse

# The event listener will be running in this block  事件监听器将在此块中运行
with mouse.Events() as events:
    # Block at most one second  最多阻塞1秒
    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))

To iterate over mouse events, use the following code:
要遍历鼠标事件,使用以下代码:

from pynput import mouse

# The event listener will be running in this block  事件监听器将在此块中运行
with mouse.Events() as events:
    for event in events:
        if event.button == mouse.Button.right:
            break
        else:
            print('Received event {}'.format(event))

Please note that the iterator method does not support non-blocking operation, so it will wait for at least one mouse event.
请注意,迭代器方法不支持非阻塞操作,因此它将等待至少一个鼠标事件。

The events will be instances of the inner classes found in pynput.mouse.Events.
这些事件将是在pynput.mouse.Events中找到的内部类的实例。

Ensuring consistent coordinates between listener and controller on Windows
确保Windows上的侦听器和控制器之间的协调一致

Recent versions of _ Windows _ support running legacy applications scaled when the system scaling has been increased beyond 100%. This allows old applications to scale, albeit with a blurry look, and avoids tiny, unusable user interfaces.
Windows的最新版本支持在系统扩展超过100%时运行遗留应用程序。这允许旧的应用程序扩展,尽管看起来很模糊,并避免了小的,不可用的用户界面。

This scaling is unfortunately inconsistently applied to a mouse listener and a controller: the listener will receive physical coordinates, but the controller has to work with scaled coordinates.
不幸的是,这种缩放不适用于鼠标侦听器和控制器:侦听器将接收物理坐标,但控制器必须使用缩放的坐标。

This can be worked around by telling Windows that your application is DPI aware. This is a process global setting, so _ pynput _ cannot do it automatically. Do enable DPI awareness, run the following code:
这可以通过告诉Windows你的应用程序是DPI感知的来解决。这是一个进程全局设置,所以_ pynput _不能自动执行。启用DPI感知功能,运行以下代码:

import ctypes


PROCESS_PER_MONITOR_DPI_AWARE = 2

ctypes.windll.shcore.SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE)
Reference
参考
class pynput.mouse.Controller pynput.mouse.Controller类

A controller for sending virtual mouse events to the system.
向系统发送虚拟鼠标事件的控制器。

class Controller(object):
    """A controller for sending virtual mouse events to the system.
    """
    def __init__(self):
        self._log = _logger(self.__class__)

    @property
    def position(self):
        """The current position of the mouse pointer.

        This is the tuple ``(x, y)``, and setting it will move the pointer.
        """
        return self._position_get()

    @position.setter
    def position(self, pos):
        self._position_set(pos)

    def scroll(self, dx, dy):
        """Sends scroll events.

        :param int dx: The horizontal scroll. The units of scrolling is
            undefined.

        :param int dy: The vertical scroll. The units of scrolling is
            undefined.

        :raises ValueError: if the values are invalid, for example out of
            bounds
        """
        self._scroll(dx, dy)


    def press(self, button):
        """Emits a button press event at the current position.

        :param Button button: The button to press.
        """
        self._press(button)


    def release(self, button):
        """Emits a button release event at the current position.

        :param Button button: The button to release.
        """
        self._release(button)


    def move(self, dx, dy):
        """Moves the mouse pointer a number of pixels from its current
        position.

        :param int x: The horizontal offset.

        :param int dy: The vertical offset.

        :raises ValueError: if the values are invalid, for example out of
            bounds
        """
        self.position = tuple(sum(i) for i in zip(self.position, (dx, dy)))


    def click(self, button, count=1):
        """Emits a button click event at the current position.

        The default implementation sends a series of press and release events.

        :param Button button: The button to click.

        :param int count: The number of clicks to send.
        """
        with self as controller:
            for _ in range(count):
                controller.press(button)
                controller.release(button)


    def __enter__(self):
        """Begins a series of clicks.

        In the default :meth:`click` implementation, the return value of this
        method is used for the calls to :meth:`press` and :meth:`release`
        instead of ``self``.

        The default implementation is a no-op.
        """
        return self

    def __exit__(self, exc_type, value, traceback):
        """Ends a series of clicks.
        """
        pass

    def _position_get(self):
        """The implementation of the getter for :attr:`position`.

        This is a platform dependent implementation.
        """
        raise NotImplementedError()

    def _position_set(self, pos):
        """The implementation of the setter for :attr:`position`.

        This is a platform dependent implementation.
        """
        raise NotImplementedError()

    def _scroll(self, dx, dy):
        """The implementation of the :meth:`scroll` method.

        This is a platform dependent implementation.
        """
        raise NotImplementedError()

    def _press(self, button):
        """The implementation of the :meth:`press` method.

        This is a platform dependent implementation.
        """
        raise NotImplementedError()

    def _release(self, button):
        """The implementation of the :meth:`release` method.

        This is a platform dependent implementation.
        """
        raise NotImplementedError()

click(button, count=1)
点击(按钮,数= 1)

Emits a button click event at the current position.
在当前位置发出按钮单击事件。
The default implementation sends a series of press and release events.
默认实现发送一系列新闻和发布事件。

Parameters:
参数:

  • button (Button) – The button to click. button (Button)-点击的按钮。
  • count (int) – The number of clicks to send. count (int) -要发送的点击次数。
    def click(self, button, count=1):
        """Emits a button click event at the current position.

        The default implementation sends a series of press and release events.

        :param Button button: The button to click.

        :param int count: The number of clicks to send.
        """
        with self as controller:
            for _ in range(count):
                controller.press(button)
                controller.release(button)

move(dx, dy)
移动(dx, dy)

Moves the mouse pointer a number of pixels from its current position.
将鼠标指针从当前位置移动若干像素。

Parameters:
参数:

  • x (int) – The horizontal offset. x (int) -水平偏移量。
  • dy (int) – The vertical offset. dy (int) -垂直偏移量。

Raises:
举例:
ValueError – if the values are invalid, for example out of bounds
ValueError -如果值是无效的,例如越界

    def move(self, dx, dy):
        """Moves the mouse pointer a number of pixels from its current
        position.

        :param int x: The horizontal offset.

        :param int dy: The vertical offset.

        :raises ValueError: if the values are invalid, for example out of
            bounds
        """
        self.position = tuple(sum(i) for i in zip(self.position, (dx, dy)))

position
位置

The current position of the mouse pointer.
鼠标指针的当前位置。
This is the tuple (x, y), and setting it will move the pointer.
这是元组(x, y),设置它将移动指针。

press(button)
Emits a button press event at the current position.
在当前位置触发按钮按下事件。
Parameters: button (Button) – The button to press.
参数:button (Button)—按下的按钮。

    def press(self, button):
        """Emits a button press event at the current position.

        :param Button button: The button to press.
        """
        self._press(button)

release(button)
Emits a button release event at the current position.
在当前位置触发按钮释放事件。
Parameters: button (Button) – The button to release.
参数:button (Button)-释放按钮。

    def release(self, button):
        """Emits a button release event at the current position.

        :param Button button: The button to release.
        """
        self._release(button)

scroll(dx, dy)
Sends scroll events.
发送滚动事件。

Parameters:
参数:

  • dx (int) – The horizontal scroll. The units of scrolling is undefined.
    dx (int) -水平滚动。未定义滚动的单位。
  • dy (int) – The vertical scroll. The units of scrolling is undefined.
    dy (int) -垂直滚动。未定义滚动的单位。

Raises:
举例:
ValueError – if the values are invalid, for example out of bounds
ValueError -如果值是无效的,例如越界

    def scroll(self, dx, dy):
        """Sends scroll events.

        :param int dx: The horizontal scroll. The units of scrolling is
            undefined.

        :param int dy: The vertical scroll. The units of scrolling is
            undefined.

        :raises ValueError: if the values are invalid, for example out of
            bounds
        """
        self._scroll(dx, dy)

class pynput.mouse.Listener(on_move=None, on_click=None, on_scroll=None, suppress=False, **kwargs)
类pynput.mouse。监听(on_move=None, on_click=None, on_scroll=None, suppress=False, **kwargs)
A listener for mouse events.
鼠标事件的监听器。

class Listener(AbstractListener):
    """A listener for mouse 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()

    This class inherits from :class:`threading.Thread` and supports all its
    methods. It will set :attr:`daemon` to ``True`` when created.

    :param callable on_move: 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 :class:`StopException` or
        returns ``False``, the listener is stopped.

    :param callable on_click: 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
        :class:`Button` values and ``pressed`` is whether the button was
        pressed.

        If this callback raises :class:`StopException` or returns ``False``,
        the listener is stopped.

    :param callable on_scroll: 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 :class:`StopException` or returns ``False``,
        the listener is stopped.

    :param bool suppress: Whether to suppress events. Setting this to ``True``
        will prevent the input events from being passed to the rest of the
        system.

    :param kwargs: 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 <https://docs.microsoft.com/en-gb/windows/win32/api/winuser/ns-winuser-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.
    """
    def __init__(self, on_move=None, on_click=None, on_scroll=None,
                 suppress=False, **kwargs):
        self._log = _logger(self.__class__)
        prefix = self.__class__.__module__.rsplit('.', 1)[-1][1:] + '_'
        self._options = {
            key[len(prefix):]: value
            for key, value in kwargs.items()
            if key.startswith(prefix)}
        super(Listener, self).__init__(
            on_move=on_move, on_click=on_click, on_scroll=on_scroll,
            suppress=suppress)

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()

This class inherits from threading.Thread and supports all its methods. It will set daemon to True when created.
这个类继承自threading。线程,并支持其所有方法。它将在创建时将daemon设置为True。

Parameters:
参数:

  • on_move (callable) –
    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.
    它将与参数(x, y)一起被调用,参数是新的指针位置。如果这个回调引发StopException或返回False,监听器将停止。
  • on_click (callable) –
    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.
    它将通过参数(x, y, button, pressed)被调用,其中(x, y)是新的指针位置,button是按钮值之一,pressed是按钮是否被按下。
    If this callback raises StopException or returns False, the listener is stopped.
    如果这个回调引发StopException或返回False,监听器将停止。
  • on_scroll (callable) –
    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.
    它将被参数(x, y, dx, dy)调用,其中(x, y)是新的指针位置,(dx, dy)是滚动向量。
    If this callback raises StopException or returns False, the listener is stopped.
    如果这个回调引发StopException或返回False,监听器将停止。
  • suppress (bool) – Whether to suppress events. Setting this to True will prevent the input events from being passed to the rest of the system.
    是否抑制事件。将此设置为True将防止输入事件被传递到系统的其余部分。
  • kwargs –
    Any non-standard platform dependent options. These should be prefixed with the platform name thus: darwin_, xorg_ or win32_.
    任何非标准平台相关选项。它们应该以平台名作为前缀,如:darwin_, xorg_或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.
    一个接受参数(event_type, event)的可调用对象,其中event_type是任何与鼠标相关的事件类型常量,event是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.
    这个可调用对象可以使用Quartz.CGEventSetIntegerValueField这样的函数自由地修改事件。如果此可调用对象没有返回事件,则在系统范围内抑制该事件。

  • win32_event_filter
    A callable taking the arguments (msg, data), where msg is the current message, and data associated data as a MSLLHOOKSTRUCT.
    接受参数(msg, data)的可调用对象,其中msg是当前消息,数据关联的数据作为MSLLHOOKSTRUCT。
    If this callback returns False, the event will not be propagated to the listener callback.
    如果该回调函数返回False,则该事件将不会传播到侦听器回调函数。
    If self.suppress_event() is called, the event is suppressed system wide.
    如果self.suppress_event()被调用,则该事件在系统范围内被抑制。

__ init__(on_move=None, on_click=None, on_scroll=None, suppress=False, ** kwargs)

    def __init__(self, on_move=None, on_click=None, on_scroll=None,
                 suppress=False, **kwargs):
        self._log = _logger(self.__class__)
        prefix = self.__class__.__module__.rsplit('.', 1)[-1][1:] + '_'
        self._options = {
            key[len(prefix):]: value
            for key, value in kwargs.items()
            if key.startswith(prefix)}
        super(Listener, self).__init__(
            on_move=on_move, on_click=on_click, on_scroll=on_scroll,
            suppress=suppress)

This constructor should always be called with keyword arguments.
调用这个构造函数时应该始终带关键字参数。
Arguments are:
参数:

  • group should be None; reserved for future extension when a ThreadGroup class is implemented.
    group应该为None;保留在ThreadGroup类实现时用于将来扩展。
  • target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
    target是run()方法要调用的可调用对象。默认为None,表示不调用任何内容。
  • name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
    name是线程名。默认情况下,唯一名称以“Thread-N”的形式构造,其中N是一个小的十进制数。
  • args is the argument tuple for the target invocation. Defaults to ().
    args是目标调用的参数元组。默认为()。
  • kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
    kwargs是目标调用的关键字参数字典。默认为{}。
  • If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__ init__()) before doing anything else to the thread.
  • 如果子类重写了构造函数,它必须确保在对线程做任何其他事情之前调用基类构造函数(thread. __ init__())。

running
Whether the listener is currently running.
侦听器当前是否正在运行。

start()
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.
每个线程对象最多只能调用一次。它安排在单独的控制线程中调用对象的run()方法。
This method will raise a RuntimeError if called more than once on the same thread object.
如果在同一个线程对象上多次调用此方法,将引发RuntimeError。

stop()
Stops listening for events.
停止监听事件。
When this method returns, no more events will be delivered. Once this method has been called, the listener instance cannot be used any more, since a listener is a threading.Thread, and once stopped it cannot be restarted.
当此方法返回时,将不再交付任何事件。一旦调用了这个方法,侦听器实例就不能再使用了,因为侦听器是一个线程。线程,一旦停止就不能重新启动。
To resume listening for event, a new listener must be created.
要继续监听事件,必须创建一个新的监听器。

wait()
Waits for this listener to become ready.
等待这个听众准备好。

Handling the keyboard

处理键盘

The package pynput.keyboard contains classes for controlling and monitoring the keyboard.
pynput.keyboard包包含用于控制和监视键盘的类。

Controlling the keyboard
控制键盘

Use pynput.keyboard.Controller like this:
像这样使用pynput.keyboard.Controller:

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'
# 键入小写字母a;即使没有钥匙,这个也能用
# 物理键盘被标记为“A”
keyboard.press('a')
keyboard.release('a')

# Type two upper case As    键入两个大写的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
# 使用快捷类型方法键入'Hello World'
keyboard.type('Hello World')
Monitoring the keyboard
监控键盘

Use pynput.keyboard.Listener like this:
像这样使用pynput.keyboard.Listener:

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()

A keyboard listener is a threading.Thread, and all callbacks will be invoked from the thread.
键盘监听器是一个线程。线程,所有的回调函数都将从线程中调用。
Call pynput.keyboard.Listener.stop from anywhere, raise StopException or return False from a callback to stop the listener.
可以在任何地方调用pynput.keyboard.Listener.stop,引发StopException或从回调函数中返回False以停止侦听器。
The key parameter passed to callbacks is a pynput.keyboard.Key, for special keys, a pynput.keyboard.KeyCode for normal alphanumeric keys, or just None for unknown keys.
传递给回调函数的key参数是一个pynput.keyboard。Key,用于特殊的键,一个pynput.keyboard。普通字母数字键的键码,未知键的键码为None。
When using the non-blocking version above, the current thread will continue executing. This might be necessary when integrating with other GUI frameworks that incorporate a main-loop, but when run from a script, this will cause the program to terminate immediately.
当使用上面的非阻塞版本时,当前线程将继续执行。当与包含主循环的其他GUI框架集成时,这可能是必要的,但当从脚本运行时,这将导致程序立即终止。

The keyboard listener thread
键盘监听器线程

The listener callbacks are invoked directly from an operating thread on some platforms, notably Windows.
监听器回调函数在某些平台上直接从操作线程调用,特别是在Windows上。
This means that long running procedures and blocking operations should not be invoked from the callback, as this risks freezing input for all processes.
这意味着不应该从回调调用长时间运行的过程和阻塞操作,因为这可能会冻结所有进程的输入。
A possible workaround is to just dispatch incoming messages to a queue, and let a separate thread handle them.
一种可能的解决方案是只将传入消息分派到队列,并让单独的线程处理它们。

Handling keyboard listener errors
处理键盘监听器错误

If a callback handler raises an exception, the listener will be stopped. Since callbacks run in a dedicated thread, the exceptions will not automatically be reraised.
如果回调处理程序引发异常,侦听器将停止。由于回调函数运行在专用线程中,因此异常不会被自动重新引发。
To be notified about callback errors, call Thread.join on the listener instance:
要得到回调错误的通知,请调用Thread.join监听器实例:

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]))
Toggling event listening for the keyboard listener
切换键盘监听器的事件监听

Once pynput.keyboard.Listener.stop has been called, the listener cannot be restarted, since listeners are instances of threading.Thread.
一旦pynput.keyboard.Listener。已调用stop,则无法重新启动侦听器,因为侦听器是thread . thread的实例。
If your application requires toggling listening events, you must either add an internal flag to ignore events when not required, or create a new listener when resuming listening.
如果您的应用程序需要切换监听事件,您必须添加一个内部标志来忽略不需要的事件,或者在恢复监听时创建一个新的监听器。

Synchronous event listening for the keyboard listener
监听键盘监听器的同步事件

To simplify scripting, synchronous event listening is supported through the utility class pynput.keyboard.Events. This class supports reading single events in a non-blocking fashion, as well as iterating over all events.
为了简化脚本编写,通过实用程序类pynput.keyboard.Events支持同步事件监听。该类支持以非阻塞方式读取单个事件,以及遍历所有事件。
To read a single event, use the following code:
要读取单个事件,使用以下代码:

from pynput import keyboard

# The event listener will be running in this block
# 事件监听器将在此块中运行
with keyboard.Events() as events:
    # Block at most one second
    # 最多阻塞1秒
    event = events.get(1.0)
    if event is None:
        print('You did not press a key within one second')
    else:
        print('Received event {}'.format(event))

To iterate over keyboard events, use the following code:
要遍历键盘事件,使用以下代码:

from pynput import keyboard

# The event listener will be running in this block
# 事件监听器将在这个块中运行
with keyboard.Events() as events:
    for event in events:
        if event.key == keyboard.Key.esc:
            break
        else:
            print('Received event {}'.format(event))

Please note that the iterator method does not support non-blocking operation, so it will wait for at least one keyboard event.
请注意,iterator方法不支持非阻塞操作,因此它将等待至少一个键盘事件。
The events will be instances of the inner classes found in pynput.keyboard.Events.
这些事件将是在pynput.keyboard.Events中找到的内部类的实例。

Global hotkeys
全球热键

A common use case for keyboard monitors is reacting to global hotkeys. Since a listener does not maintain any state, hotkeys involving multiple keys must store this state somewhere.
键盘显示器的一个常见用例是响应全局热键。由于侦听器不维护任何状态,涉及多个键的热键必须在某处存储该状态。
pynput provides the class pynput.keyboard.HotKey for this purpose. It contains two methods to update the state, designed to be easily interoperable with a keyboard listener:
pynput提供了类pynput.keyboard。用于此目的的热键。它包含两种更新状态的方法,设计为与键盘监听器易于互操作:
pynput.keyboard.HotKey.press and pynput.keyboard.HotKey.release which can be directly passed as listener callbacks.
pynput.keyboard.HotKey.press和pynput.keyboard.HotKey.release,可以直接作为监听器回调传递。
The intended usage is as follows:
预期用途如下:

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()

This will create a hotkey, and then use a listener to update its state. Once all the specified keys are pressed simultaneously, on_activate will be invoked.
这将创建一个热键,然后使用监听器更新其状态。一旦同时按下所有指定的键,on_activate将被调用。
Note that keys are passed through pynput.keyboard.Listener.canonical before being passed to the HotKey instance. This is to remove any modifier state from the key events, and to normalise modifiers with more than one physical button.
注意,键是通过pynput.keyboard.Listener传递的。在传递给热键实例之前进行规范。这是为了从键事件中移除任何修饰符状态,并使用多个物理按钮来规范修饰符。
The method pynput.keyboard.HotKey.parse is a convenience function to transform shortcut strings to key collections. Please see its documentation for more information.
pynput.keyboard.HotKey.parse是一个方便的函数,可以将快捷字符串转换为键集合。请参阅其文档了解更多信息。
To register a number of global hotkeys, use the convenience class pynput.keyboard.GlobalHotKeys:
要注册多个全局热键,请使用便捷性类pynput.keyboard.GlobalHotKeys:

from pynput import keyboard

def on_activate_h():
    print('<ctrl>+<alt>+h pressed')

def on_activate_i():
    print('<ctrl>+<alt>+i pressed')

with keyboard.GlobalHotKeys({
        '<ctrl>+<alt>+h': on_activate_h,
        '<ctrl>+<alt>+i': on_activate_i}) as h:
    h.join()

Reference

参考

class pynput.keyboard.Controller
pynput.keyboard.Controller类

A controller for sending virtual keyboard events to the system.
向系统发送虚拟键盘事件的控制器。

class Controller(object):
    """A controller for sending virtual keyboard events to the system.
    """
    #: The virtual key codes
    _KeyCode = KeyCode

    #: The various keys.
    _Key = Key

    class InvalidKeyException(Exception):
        """The exception raised when an invalid ``key`` parameter is passed to
        either :meth:`Controller.press` or :meth:`Controller.release`.

        Its first argument is the ``key`` parameter.
        """
        pass


    class InvalidCharacterException(Exception):
        """The exception raised when an invalid character is encountered in
        the string passed to :meth:`Controller.type`.

        Its first argument is the index of the character in the string, and the
        second the character.
        """
        pass


    def __init__(self):
        self._log = _logger(self.__class__)
        self._modifiers_lock = threading.RLock()
        self._modifiers = set()
        self._caps_lock = False
        self._dead_key = None

    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


    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)


    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)


    def touch(self, key, is_press):
        """Calls either :meth:`press` or :meth:`release` depending on the value
        of ``is_press``.

        :param key: The key to press or release.

        :param bool is_press: Whether to press the key.

        :raises InvalidKeyException: if the key is invalid
        """
        if is_press:
            self.press(key)
        else:
            self.release(key)


    @contextlib.contextmanager
    def pressed(self, *args):
        """Executes a block with some keys pressed.

        :param keys: The keys to keep pressed.
        """
        for key in args:
            self.press(key)

        try:
            yield
        finally:
            for key in reversed(args):
                self.release(key)


    def type(self, string):
        """Types a string.

        This method will send all key presses and releases necessary to type
        all characters in the string.

        :param str string: The string to type.

        :raises InvalidCharacterException: if an untypable character is
            encountered
        """
        from . import _CONTROL_CODES
        for i, character in enumerate(string):
            key = _CONTROL_CODES.get(character, character)
            try:
                self.press(key)
                self.release(key)

            except (ValueError, self.InvalidKeyException):
                raise self.InvalidCharacterException(i, character)


    @property
    @contextlib.contextmanager
    def modifiers(self):
        """The currently pressed modifier keys.

        Please note that this reflects only the internal state of this
        controller, and not the state of the operating system keyboard buffer.
        This property cannot be used to determine whether a key is physically
        pressed.

        Only the generic modifiers will be set; when pressing either
        :attr:`Key.shift_l`, :attr:`Key.shift_r` or :attr:`Key.shift`, only
        :attr:`Key.shift` will be present.

        Use this property within a context block thus::

            with controller.modifiers as modifiers:
                with_block()

        This ensures that the modifiers cannot be modified by another thread.
        """
        with self._modifiers_lock:
            yield set(
                self._as_modifier(modifier)
                for modifier in self._modifiers)

    @property
    def alt_pressed(self):
        """Whether any *alt* key is pressed.

        Please note that this reflects only the internal state of this
        controller. See :attr:`modifiers` for more information.
        """
        with self.modifiers as modifiers:
            return self._Key.alt in modifiers

    @property
    def alt_gr_pressed(self):
        """Whether *altgr* is pressed.

        Please note that this reflects only the internal state of this
        controller. See :attr:`modifiers` for more information.
        """
        with self.modifiers as modifiers:
            return self._Key.alt_gr in modifiers

    @property
    def ctrl_pressed(self):
        """Whether any *ctrl* key is pressed.

        Please note that this reflects only the internal state of this
        controller. See :attr:`modifiers` for more information.
        """
        with self.modifiers as modifiers:
            return self._Key.ctrl in modifiers

    @property
    def shift_pressed(self):
        """Whether any *shift* key is pressed, or *caps lock* is toggled.

        Please note that this reflects only the internal state of this
        controller. See :attr:`modifiers` for more information.
        """
        if self._caps_lock:
            return True

        with self.modifiers as modifiers:
            return self._Key.shift in modifiers

    def _resolve(self, key):
        """Resolves a key to a :class:`KeyCode` instance.

        This method will convert any key representing a character to uppercase
        if a shift modifier is active.

        :param key: The key to resolve.

        :return: a key code, or ``None`` if it cannot be resolved
        """
        # Use the value for the key constants
        if key in (k for k in self._Key):
            return key.value

        # Convert strings to key codes
        if isinstance(key, six.string_types):
            if len(key) != 1:
                raise ValueError(key)
            return self._KeyCode.from_char(key)

        # Assume this is a proper key
        if isinstance(key, self._KeyCode):
            if key.char is not None and self.shift_pressed:
                return self._KeyCode(vk=key.vk, char=key.char.upper())
            else:
                return key

    def _update_modifiers(self, key, is_press):
        """Updates the current modifier list.

        If ``key`` is not a modifier, no action is taken.

        :param key: The key being pressed or released.
        """
        # Check whether the key is a modifier
        if self._as_modifier(key):
            with self._modifiers_lock:
                if is_press:
                    self._modifiers.add(key)
                else:
                    try:
                        self._modifiers.remove(key)
                    except KeyError:
                        pass

    def _as_modifier(self, key):
        """Returns a key as the modifier used internally if defined.

        This method will convert values like :attr:`Key.alt_r.value` and
        :attr:`Key.shift_l.value` to :attr:`Key.alt` and :attr:`Key.shift`.

        :param key: The possible modifier key.

        :return: the base modifier key, or ``None`` if ``key`` is not a
            modifier
        """
        from . import _NORMAL_MODIFIERS
        return _NORMAL_MODIFIERS.get(key, None)

    def _handle(self, key, is_press):
        """The platform implementation of the actual emitting of keyboard
        events.

        This is a platform dependent implementation.

        :param Key key: The key to handle.

        :param bool is_press: Whether this is a key press event.
        """
        raise NotImplementedError()

exception InvalidCharacterException
异常InvalidCharacterException
The exception raised when an invalid character is encountered in the string passed to Controller.type().
传递给Controller.type()的字符串中遇到无效字符时引发的异常。
Its first argument is the index of the character in the string, and the second the character.
它的第一个参数是字符串中字符的索引,第二个参数是字符。

class InvalidCharacterException(Exception):
        """
        The exception raised when an invalid character is encountered in the string passed to :meth:`Controller.type`.
        传递给:meth: ' Controller.type '的字符串中遇到无效字符时引发的异常。

        Its first argument is the index of the character in the string, and the second the character.
        它的第一个参数是字符串中字符的索引,第二个参数是字符。
        """
        pass

exception InvalidKeyException
异常InvalidKeyException
The exception raised when an invalid key parameter is passed to either Controller.press() or Controller.release().
当一个无效的键参数被传递给Controller.press()或Controller.release()时引发的异常。
Its first argument is the key parameter.
它的第一个参数是key参数。

class InvalidKeyException(Exception):
        """
        The exception raised when an invalid ``key`` parameter is passed to
        当一个无效的' ' key ' '参数被传递给时引发的异常
        either :meth:`Controller.press` or :meth:`Controller.release`.
        甲:“控制器。”或:甲:“Controller.release”。

        Its first argument is the ``key`` parameter.
        它的第一个参数是“key”参数。
        """
        pass

alt_gr_pressed
Whether altgr is pressed.
altgr是否压下。
Please note that this reflects only the internal state of this controller. See modifiers for more information.
请注意,这只反映了该控制器的内部状态。有关更多信息,请参阅modifiers。
alt_pressed
Whether any alt key is pressed.
是否按了alt键。
Please note that this reflects only the internal state of this controller. See modifiers for more information.
请注意,这只反映了该控制器的内部状态。有关更多信息,请参阅modifiers。
ctrl_pressed
Whether any ctrl key is pressed.
是否按下了ctrl键。
Please note that this reflects only the internal state of this controller. See modifiers for more information.
请注意,这只反映了该控制器的内部状态。有关更多信息,请参阅modifiers。
modifiers
The currently pressed modifier keys.
当前按下的修改键。
Please note that this reflects only the internal state of this controller, and not the state of the operating system keyboard buffer. This property cannot be used to determine whether a key is physically pressed.
请注意,这只反映了控制器的内部状态,而不是操作系统键盘缓冲区的状态。此属性不能用于确定某个键是否被物理按下。
Only the generic modifiers will be set; when pressing either Key.shift_l, Key.shift_r or Key.shift, only Key.shift will be present.
只有通用修饰符会被设置;当按任意一个键。shift_l,关键。shift_r或关键。转变,唯一的关键。转移将会出现。
Use this property within a context block thus:
在上下文块中使用此属性如下:

with controller.modifiers as modifiers:
    with_block()

This ensures that the modifiers cannot be modified by another thread.
这确保了修饰符不能被其他线程修改。
press(key)
Presses a key.
按下某个键。
A key may be either a string of length 1, one of the Key members or a KeyCode.
键可以是长度为1的字符串、键成员之一或键代码。
Strings will be transformed to KeyCode using KeyCode.char(). Members of Key will be translated to their value().
字符串将使用KeyCode.char()转换为KeyCode。Key的成员将被转换为它们的value()。
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 如果key是一个字符串,但它的长度不是1
    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`.
        一个键可以是一个长度为1的字符串,一个:class: ' key '成员或一个: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`.
        字符串将使用:meth: ' KeyCode.char '被转换为:class: ' KeyCode '。:class: ' Key '的成员将被转换为它们的: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``  如果' ' key ' '是字符串,但它的长度不是' ' 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

*pressed(args)
Executes a block with some keys pressed.
执行一个按了一些键的块。
Parameters:
参数:
keys – The keys to keep pressed. 要一直按的键。

release(key)
Releases a key.
释放的一个键。
A key may be either a string of length 1, one of the Key members or a KeyCode.
键可以是长度为1的字符串、键成员之一或键代码。
Strings will be transformed to KeyCode using KeyCode.char(). Members of Key will be translated to their value().
字符串将使用KeyCode.char()转换为KeyCode。Key的成员将被转换为它们的value()。
Parameters:
参数:
key – The key to release. If this is a string, it is passed to touches() and the returned releases are used.
如果这是一个字符串,它将被传递给touches()并使用返回的释放。
Raises:
例如:

  • InvalidKeyException – if the key is invalid 如果键无效
  • ValueError – if key is a string, but its length is not 1 如果key是一个字符串,但它的长度不是1

shift_pressed
Whether any shift key is pressed, or caps lock is toggled.
是否按下任何shift键或切换大写锁定。
Please note that this reflects only the internal state of this controller. See modifiers for more information.
请注意,这只反映了该控制器的内部状态。有关更多信息,请参阅modifiers。
tap(key)
Presses and releases a key.
按下并释放一个键。

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)

This is equivalent to the following code:
这相当于下面的代码:

controller.press(key)
controller.release(key)

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如果key是一个字符串,但它的长度不是1
    touch(key, is_press)
    Calls either press() or release() depending on the value of is_press.
    根据is_press的值调用press()或release()。
    Parameters:
    参数:
  • key – The key to press or release.按下或释放的键。
  • is_press (bool) – Whether to press the key.是否按下该键。
    Raises:
    举例:
    InvalidKeyException – if the key is invalid如果键无效
def touch(self, key, is_press):
        """Calls either :meth:`press` or :meth:`release` depending on the value
        of ``is_press``.

        :param key: The key to press or release.

        :param bool is_press: Whether to press the key.

        :raises InvalidKeyException: if the key is invalid
        """
        if is_press:
            self.press(key)
        else:
            self.release(key)

type(string)
Types a string.
一个字符串类型。
This method will send all key presses and releases necessary to type all characters in the string.
此方法将发送输入字符串中所有字符所需的所有按键和释放。
Parameters:
参数:
string (str) – The string to type.要输入的字符串。
Raises:
举例:
InvalidCharacterException – if an untypable character is encountered如果遇到无法输入的字符

def type(self, string):
        """Types a string.

        This method will send all key presses and releases necessary to type
        all characters in the string.

        :param str string: The string to type.

        :raises InvalidCharacterException: if an untypable character is
            encountered
        """
        from . import _CONTROL_CODES
        for i, character in enumerate(string):
            key = _CONTROL_CODES.get(character, character)
            try:
                self.press(key)
                self.release(key)

            except (ValueError, self.InvalidKeyException):
                raise self.InvalidCharacterException(i, character)

**class pynput.keyboard.Listener(on_press=None, on_release=None, suppress=False, kwargs)
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()

This class inherits from threading.Thread and supports all its methods. It will set daemon to True when created.
这个类继承自threading。线程,并支持其所有方法。它将在创建时将daemon设置为True。

Parameters:
参考:

  • on_press (callable) –
    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.
    它将与参数(key)一起被调用,其中key是一个键代码,如果键是未知的,则是一个键或None。
  • on_release (callable) –
    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.
    它将与参数(key)一起被调用,其中key是一个键代码,如果键是未知的,则是一个键或None。
  • suppress (bool) – Whether to suppress events. Setting this to True will prevent the input events from being passed to the rest of the system.
    是否抑制事件。将此设置为True将防止输入事件被传递到系统的其余部分。
  • kwargs –
    Any non-standard platform dependent options. These should be prefixed with the platform name thus: darwin_, xorg_ or win32_.
    任何非标准平台相关选项。它们应该以平台名作为前缀,如:darwin_, xorg_或win32_。

Supported values are:
支持的值是:

  • darwin_intercept
    A callable taking the arguments (event_type, event), where event_type is Quartz.kCGEventKeyDown or Quartz.kCGEventKeyDown, 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.
    一个接受参数(event_type, event)的可调用对象,其中event_type是Quartz。kCGEventKeyDown或者石英。kCGEventKeyDown,而event是CGEventRef。
    这个可调用对象可以使用Quartz.CGEventSetIntegerValueField这样的函数自由地修改事件。如果此可调用对象没有返回事件,则在系统范围内抑制该事件。
  • win32_event_filter
    A callable taking the arguments (msg, data), where msg is the current message, and data associated data as a KBDLLHOOKSTRUCT.
    If this callback returns False, the event will not be propagated to the listener callback.
    接受参数(msg, data)的可调用对象,其中msg是当前消息,数据关联数据为KBDLLHOOKSTRUCT。
    如果该回调函数返回False,则该事件将不会传播到侦听器回调函数。
    If self.suppress_event() is called, the event is suppressed system wide.
    如果self.suppress_event()被调用,则该事件在系统范围内被抑制。

**__ init__(on_press=None, on_release=None, suppress=False, kwargs)

def __init__(self, on_press=None, on_release=None, suppress=False,
                 **kwargs):
        self._log = _logger(self.__class__)
        prefix = self.__class__.__module__.rsplit('.', 1)[-1][1:] + '_'
        self._options = {
            key[len(prefix):]: value
            for key, value in kwargs.items()
            if key.startswith(prefix)}
        super(Listener, self).__init__(
            on_press=on_press, on_release=on_release, suppress=suppress)

This constructor should always be called with keyword arguments. Arguments are:
调用这个构造函数时应该始终带关键字参数。参数:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
group应该为None;保留在ThreadGroup类实现时用于将来扩展。
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
target是run()方法要调用的可调用对象。默认为None,表示不调用任何内容。
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
name是线程名。默认情况下,唯一名称以“Thread-N”的形式构造,其中N是一个小的十进制数。
args is the argument tuple for the target invocation. Defaults to ().
args是目标调用的参数元组。默认为()。
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
kwargs是目标调用的关键字参数字典。默认为{}。
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__ init__()) before doing anything else to the thread.
如果子类重写了构造函数,它必须确保调用基类的构造函数(Thread。__ init__()),然后再对线程执行任何其他操作。
running
Whether the listener is currently running.
侦听器当前是否正在运行。
start()
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.
每个线程对象最多只能调用一次。它安排在单独的控制线程中调用对象的run()方法。
This method will raise a RuntimeError if called more than once on the same thread object.
如果在同一个线程对象上多次调用此方法,将引发RuntimeError。
stop()
Stops listening for events.
停止监听事件。
When this method returns, no more events will be delivered. Once this method has been called, the listener instance cannot be used any more, since a listener is a threading.Thread, and once stopped it cannot be restarted.
当此方法返回时,将不再交付任何事件。一旦调用了这个方法,侦听器实例就不能再使用了,因为侦听器是一个线程。线程,一旦停止就不能重新启动。
To resume listening for event, a new listener must be created.
要继续监听事件,必须创建一个新的监听器。
wait()
Waits for this listener to become ready.
等待这个听众准备好。

class pynput.keyboard.Key
pynput.keyboard.Key类
class Key(enum.Enum):
    """A class representing various buttons that may not correspond to
    letters. This includes modifier keys and function keys.

    The actual values for these items differ between platforms. Some platforms
    may have additional buttons, but these are guaranteed to be present
    everywhere.
    """
    #: A generic Alt key. This is a modifier.
    alt = 0

    #: The left Alt key. This is a modifier.
    alt_l = 0

    #: The right Alt key. This is a modifier.
    alt_r = 0

    #: The AltGr key. This is a modifier.
    alt_gr = 0

    #: The Backspace key.
    backspace = 0

    #: The CapsLock key.
    caps_lock = 0

    #: A generic command button. On *PC* platforms, this corresponds to the
    #: Super key or Windows key, and on *Mac* it corresponds to the Command
    #: key. This may be a modifier.
    cmd = 0

    #: The left command button. On *PC* platforms, this corresponds to the
    #: Super key or Windows key, and on *Mac* it corresponds to the Command
    #: key. This may be a modifier.
    cmd_l = 0

    #: The right command button. On *PC* platforms, this corresponds to the
    #: Super key or Windows key, and on *Mac* it corresponds to the Command
    #: key. This may be a modifier.
    cmd_r = 0

    #: A generic Ctrl key. This is a modifier.
    ctrl = 0

    #: The left Ctrl key. This is a modifier.
    ctrl_l = 0

    #: The right Ctrl key. This is a modifier.
    ctrl_r = 0

    #: The Delete key.
    delete = 0

    #: A down arrow key.
    down = 0

    #: The End key.
    end = 0

    #: The Enter or Return key.
    enter = 0

    #: The Esc key.
    esc = 0

    #: The function keys. F1 to F20 are defined.
    f1 = 0
    f2 = 0
    f3 = 0
    f4 = 0
    f5 = 0
    f6 = 0
    f7 = 0
    f8 = 0
    f9 = 0
    f10 = 0
    f11 = 0
    f12 = 0
    f13 = 0
    f14 = 0
    f15 = 0
    f16 = 0
    f17 = 0
    f18 = 0
    f19 = 0
    f20 = 0

    #: The Home key.
    home = 0

    #: A left arrow key.
    left = 0

    #: The PageDown key.
    page_down = 0

    #: The PageUp key.
    page_up = 0

    #: A right arrow key.
    right = 0

    #: A generic Shift key. This is a modifier.
    shift = 0

    #: The left Shift key. This is a modifier.
    shift_l = 0

    #: The right Shift key. This is a modifier.
    shift_r = 0

    #: The Space key.
    space = 0

    #: The Tab key.
    tab = 0

    #: An up arrow key.
    up = 0

    #: The play/pause toggle.
    media_play_pause = 0

    #: The volume mute button.
    media_volume_mute = 0

    #: The volume down button.
    media_volume_down = 0

    #: The volume up button.
    media_volume_up = 0

    #: The previous track button.
    media_previous = 0

    #: The next track button.
    media_next = 0

    #: The Insert key. This may be undefined for some platforms.
    insert = 0

    #: The Menu key. This may be undefined for some platforms.
    menu = 0

    #: The NumLock key. This may be undefined for some platforms.
    num_lock = 0

    #: The Pause/Break key. This may be undefined for some platforms.
    pause = 0

    #: The PrintScreen key. This may be undefined for some platforms.
    print_screen = 0

    #: The ScrollLock key. This may be undefined for some platforms.
    scroll_lock = 0

A class representing various buttons that may not correspond to letters. This includes modifier keys and function keys.
表示可能不对应于字母的各种按钮的类。这包括修改键和函数键。
The actual values for these items differ between platforms. Some platforms may have additional buttons, but these are guaranteed to be present everywhere.
这些项的实际值在不同平台之间有所不同。有些平台可能会有额外的按钮,但这些按钮肯定无处不在。
alt = 0
A generic Alt key. This is a modifier.
一个通用的Alt键。这是一个修饰语。

alt_gr = 0
The AltGr key. This is a modifier.
AltGr键。这是一个修饰语。

alt_l = 0
The left Alt key. This is a modifier.
左Alt键。这是一个修饰语。

alt_r = 0
The right Alt key. This is a modifier.
右Alt键。这是一个修饰语。

backspace = 0
The Backspace key.
退格键。

caps_lock = 0
The CapsLock key.
大写锁定键。

cmd = 0
A generic command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key. This may be a modifier.
通用的命令按钮。在PC平台上,这对应于超级键或Windows键,在Mac上对应于命令键。这可能是一个修饰语。

cmd_l = 0
The left command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key. This may be a modifier.
左边的命令按钮。在PC平台上,这对应于超级键或Windows键,在Mac上对应于命令键。这可能是一个修饰语。

cmd_r = 0
The right command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key. This may be a modifier.
右边的命令按钮。在PC平台上,这对应于超级键或Windows键,在Mac上对应于命令键。这可能是一个修饰语。

ctrl = 0
A generic Ctrl key. This is a modifier.
一个通用的Ctrl键。这是一个修饰语。

ctrl_l = 0
The left Ctrl key. This is a modifier.
左键Ctrl。这是一个修饰语。

ctrl_r = 0
The right Ctrl key. This is a modifier.
右Ctrl键。这是一个修饰语。

delete = 0
The Delete key.
删除键。

down = 0
A down arrow key.
向下箭头键。

end = 0
The End key.
结束键。

enter = 0
The Enter or Return key.
回车键或回车键。

esc = 0
The Esc key.
Esc键。

f1 = 0
The function keys. F1 to F20 are defined.
功能键。定义了F1到F20。

home = 0
The Home key.
主键。

insert = 0
The Insert key. This may be undefined for some platforms.
插入钥匙。这在某些平台上可能没有定义。

left = 0
A left arrow key.
一个左箭头键。

media_next = 0
The next track button.
下一个跟踪按钮。

media_play_pause = 0
The play/pause toggle.
播放/暂停切换。

media_previous = 0
The previous track button.
前面的track按钮。

media_volume_down = 0
The volume down button.
音量降低按钮。

media_volume_mute = 0
The volume mute button.
音量静音按钮。

media_volume_up = 0
The volume up button.
音量上升按钮。

menu = 0
The Menu key. This may be undefined for some platforms.
菜单的关键。这在某些平台上可能没有定义。

num_lock = 0
The NumLock key. This may be undefined for some platforms.
时键盘上的数字键。这在某些平台上可能没有定义。

page_down = 0
The PageDown key.
下页键。

page_up = 0
The PageUp key.
上页键

pause = 0
The Pause/Break key. This may be undefined for some platforms.
暂停/停止键。这在某些平台上可能没有定义。

print_screen = 0
The PrintScreen key. This may be undefined for some platforms.
屏幕截图键。这在某些平台上可能没有定义。

right = 0
A right arrow key.
右箭头键。

scroll_lock = 0
The ScrollLock key. This may be undefined for some platforms.
ScrollLock键。这在某些平台上可能没有定义。

shift = 0
A generic Shift key. This is a modifier.
一个通用的Shift键。这是一个修饰语。

shift_l = 0
The left Shift key. This is a modifier.
左Shift键。这是一个修饰语。

shift_r = 0
The right Shift key. This is a modifier.
右Shift键。这是一个修饰语。

space = 0
The Space key.
空格键。

tab = 0
The Tab key.
Tab键。

up = 0
An up arrow key.
向上箭头键。

class pynput.keyboard.KeyCode(vk=None, char=None, is_dead=False, **kwargs)
类pynput.keyboard。KeyCode(vk=None, char=None, is_dead=False, **kwargs)

A KeyCode represents the description of a key code used by the operating system.
键码表示操作系统使用的键码的描述。

class KeyCode(object):
    """
    A :class:`KeyCode` represents the description of a key code used by the
    operating system.
    """
    #: The names of attributes used as platform extensions.
    _PLATFORM_EXTENSIONS = []

    def __init__(self, vk=None, char=None, is_dead=False, **kwargs):
        self.vk = vk
        self.char = six.text_type(char) if char is not None else None
        self.is_dead = is_dead

        if self.is_dead:
            try:
                self.combining = unicodedata.lookup(
                    'COMBINING ' + unicodedata.name(self.char))
            except KeyError:
                self.is_dead = False
                self.combining = None
            if self.is_dead and not self.combining:
                raise KeyError(char)
        else:
            self.combining = None

        for key in self._PLATFORM_EXTENSIONS:
            setattr(self, key, kwargs.pop(key, None))
        if kwargs:
            raise ValueError(kwargs)


    def __repr__(self):
        if self.is_dead:
            return '[%s]' % repr(self.char)
        if self.char is not None:
            return repr(self.char)
        else:
            return '<%d>' % self.vk

    def __str__(self):
        return repr(self)

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
        if self.char is not None and other.char is not None:
            return self.char == other.char and self.is_dead == other.is_dead
        else:
            return self.vk == other.vk and all(
                getattr(self, f) == getattr(other, f)
                for f in self._PLATFORM_EXTENSIONS)

    def __hash__(self):
        return hash(repr(self))

    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)


    @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)

**classmethod from_char(char, kwargs)
Creates a key from a character.
从字符创建一个键。
Parameters:
参数:
char (str) – The character.这个角色。
Returns:
举例:
a key code一个关键的代码

    @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 from_dead(char, kwargs)
Creates a dead key.
创建一个死键。
Parameters:
参数:
char – The dead key. This should be the unicode character representing the stand alone character, such as ‘~’ for COMBINING TILDE.
char -死键。这应该是表示独立字符的unicode字符,例如用于组合波浪号的’~’。
Returns:
举例:
a key code一个关键的代码

    @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)

**classmethod from_vk(vk, kwargs)[source]
Creates a key from a virtual key code.
从虚拟密钥代码创建密钥。
Parameters:
参数:

  • vk – The virtual key code.虚拟密钥代码。
  • kwargs – Any other parameters to pass.要传递的任何其他参数。
    Returns:
    举例:
    a key code一个关键的代码
    @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)

join(key)
Applies this dead key to another key and returns the result.
将这个死键应用到另一个键上并返回结果。

    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)

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(’’)).
KeyCode.from_dead(’~’).join(KeyCode.from_char(’ ‘))等于KeyCode.from_char(’’)和KeyCode.from_dead(’’).join(KeyCode.from_dead(’~’))。

Parameters:
参数:
key (KeyCode) – The key to join with this key.要与此键连接的键。
Returns:
回报:
a key code一个关键的代码
Raises:
举例:
ValueError – if the keys cannot be joined
ValueError -如果键不能连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vicky__3021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值