Search code examples
pythonpython-3.xmultithreadingpynput

How to manage two threads, pynput mouse listener and while loop?


I have a mouse listener:

from pynput.mouse import Listener, Button

def on_click(x, y, button):
    if button == Button.left:
    xy_dict["x"] = x
    xy_dict["y"] = y
    if button == Button.right:
        raise MyException(button)

with Listener(on_click=on_click) as listener:
    listener.join()

And I also have main() function from other script. It is supposed that main() takes x and y from mouse listener, but how can I unite these two threads?


Solution

  • The context manager method (i.e. with) is only useful if you want to be able to stop the listener. If you don't need that, simply start the listener:

    listener = Listener(on_click=on_click)
    listener.start()
    

    It will automatically start as a new thread:

    https://pythonhosted.org/pynput/mouse.html#monitoring-the-mouse

    A mouse listener is a threading.Thread, and all callbacks will be invoked from the thread.

    The easiest method to access the x and y values would be to wrap this in a class and update instance attributes within the handler; or define two global variables (x and y).