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

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

尝试import time添加time.sleep(1)on_move(x, y)功能,但当你运行它时,你的鼠标会发疯。

这是整体代码:

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


慕村225694
浏览 92回答 1
1回答

手掌心

当执行某些会阻止代码的任务时,您可以使用线程来运行代码。(在您的代码中,sleep(1)将阻止代码),无论如何,这在我的电脑上运行良好:from pynput.mouse import Listenerimport timeimport threadingdef task(): # this is what you want to do.&nbsp; &nbsp; time.sleep(1)&nbsp; # <<< Tried to add it over here cuz it takes most of the process.&nbsp; &nbsp; print("After sleep 1 second")def on_move(x, y):&nbsp; &nbsp; print('Pointer moved to {0}'.format((x, y)))&nbsp; &nbsp; threading.Thread(target=task).start() # run some tasks here.def on_click(x, y, button, pressed):&nbsp; &nbsp; print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))&nbsp; &nbsp; if not pressed:&nbsp; &nbsp; &nbsp; &nbsp; return Falsedef on_scroll(x, y, dx, dy):&nbsp; &nbsp; print('Scrolled {0}'.format((x, y)))with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:&nbsp; &nbsp; listener.join()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python