moses-palmer / pynput

Sends virtual input commands
GNU Lesser General Public License v3.0
1.79k stars 248 forks source link

How to run time consuming work, it makes my mouse moving slow down #477

Closed pgshow closed 2 years ago

pgshow commented 2 years ago
import time
from pynput.mouse import Button, Controller, Listener

def on_click(x, y, button, pressed):
    if button == Button.middle and pressed:
        print("Start")
        time.sleep(10)
        print("Done")

listener1 = Listener(on_click=on_click)
listener1.start()
listener1.join()

I launch this on Windows10, after I click mouse-middle, my mouse moving become very slow in that 10 seconds. I want to put some time-consuming work in that place.

TWolczanski commented 2 years ago

You have to do this time-consuming work in a separate thread:

import time
from pynput.mouse import Button, Controller, Listener
from threading import Thread

def on_click(x, y, button, pressed):
    if button == Button.middle and pressed:
        Thread(target=time_consuming_work).start()

def time_consuming_work():
    print("Start")
    time.sleep(10)
    print("Done")

listener1 = Listener(on_click=on_click)
listener1.start()
listener1.join()
moses-palmer commented 2 years ago

As @TWolczanski suggests, you will need to move any time-consuming work to a separate thread. queue.Queue from the Python standard library can be used to notify the thread when to wake up.