使 pynput 鼠标侦听器减少资源消耗

Make pynput mouse listener less resource-hungry

我正在尝试使用来自 pynput 的 This 脚本来监控我的鼠标,但它太占用资源了。

尝试 import time 并在 on_move(x, y) 函数之后添加 time.sleep(1) 但是当你 运行 它时你的鼠标会变得疯狂。

整体代码如下:

import time

def on_move(x, y):
    print('Pointer moved to {0}'.format((x, y)))
    time.sleep(1) # <<< Tried to add it over here cuz it takes most of the process.

def on_click(x, y, button, pressed):
    print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))
    if not pressed:
        return False

def on_scroll(x, y, dx, dy):
    print('Scrolled {0}'.format((x, y)))
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

您可以在执行某些会阻塞代码的任务时使用线程 运行 您的代码。(在您的代码中,sleep(1) 会阻塞代码),无论如何,这在我的电脑:

from pynput.mouse import Listener
import time
import threading

def task(): # this is what you want to do.
    time.sleep(1)  # <<< Tried to add it over here cuz it takes most of the process.
    print("After sleep 1 second")

def on_move(x, y):
    print('Pointer moved to {0}'.format((x, y)))
    threading.Thread(target=task).start() # run some tasks here.

def on_click(x, y, button, pressed):
    print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))
    if not pressed:
        return False

def on_scroll(x, y, dx, dy):
    print('Scrolled {0}'.format((x, y)))


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()