为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕村225694 2023-07-18 10:20:32
我正在尝试使用pynput 中的此脚本来监视我的鼠标,但它太占用资源了。尝试import time添加time.sleep(1)后on_move(x, y)功能,但当你运行它时,你的鼠标会发疯。这是整体代码:import timedef 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 Falsedef 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()
查看完整描述

1 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

当执行某些会阻止代码的任务时,您可以使用线程来运行代码。(在您的代码中,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()


查看完整回答
反对 回复 2023-07-18
  • 1 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信