每 0.2 秒发送一次鼠标位置 pynput

Send mouse position every 0.2 seconds pynput

我正在使用 pynput 每 0.2 秒发送一次鼠标位置。 我试过计时:

from pynput.mouse import Button, Listener as MouseListener

def on_move(x,y):
    global start_time
    time_passed = start_time - time.time()

    if time_passed >= 0.2:
        command = f'{None}\n{x}\n{y}'
        commands_q.put(command)
    start_time = time.time()

mouse_listener = MouseListener(on_move=on_move)
mouse_listener.start()
mouse_listener.join()

此代码无效。它破坏了我的程序 mid 运行(程序使用套接字发送鼠标的位置)

有什么建议吗?

我不确定你想要达到什么目的,但像这样的简单代码可以为你工作:

from pynput.mouse import Controller
import time
mouse = Controller()

while True :
    command = mouse.position
    commands_q.put(command)
    time.sleep(0.2)

对于两个监听鼠标和键盘,使用这种代码:

from pynput.mouse import Controller as mouse_control
from pynput import keyboard as key_control

mouse = mouse_control() #mouse controller

def on_press (key) :
    print(key.char)

listener = key_control.Listener(on_press=on_press) #keyboard listener
listener.start()

while True :
    command = mouse.position
    print(command)
    time.sleep(0.2)