moses-palmer / pynput

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

Stopping the listener within a loop #542

Closed gh0styxx closed 1 year ago

gh0styxx commented 1 year ago

Hello,

I'm trying to write a function which executes in a loop something few times. I would like to break it when a specific key is pressed, but I am not sure if it is possible with pynput library. I tried something like this:

def my_function(self):
        self.stop_mouse_listener()
        self.mouse_listener = MouseListener(on_click=self.on_click)
        self.start_mouse_listener()
        for i in range(0, 10):
            if(self.on_click(self.my_coordinateX, self.my_coordinateY, Button.right, True)):
                print('now breaking')
                break
            else:
                print('still in loop')
                time.sleep(0.15)

I expect that the function will stop when I press right button of mouse but I get "still in loop" few times, then once "now breaking" and after that the others "still in loop". Is there any possibility to stop it? The function my_function() is called when I press the middle button.

moses-palmer commented 1 year ago

Have you tried setting a flag inside of self.on_click and checking for that flag instead?

I would however advise against calling my_function from a pynput event handler; please see the documentation.