如何解决减少Pynput鼠标侦听器的资源消耗
我正在尝试使用来自pynput的This脚本来监视鼠标,但是它过于占用资源。
尝试使用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,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)
将阻止代码),无论如何,这在我的PC上可以正常工作:
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,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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。