我正在尝试使用来自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, 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()
答案 0 :(得分:1)
执行某些将阻止代码的任务时,您可以使用线程来运行代码。(在您的代码中,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, 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()