How to run pynput Listener simultaneously with other Python module
pynput
documentation shows examples how to monitoring the keyboard and how to monitoring the mouse
For keyboard
it looks similar for this
from pynput import keyboard
# --- functions ---
def on_press(key):
# some code
def on_release(key):
# some code
# --- main ---
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
For mouse
it looks similar for this
from pynput import mouse
# --- functions ---
def on_move(x, y):
# some code
def on_click(x, y, button, pressed):
# some code
def on_scroll(x, y, dx, dy):
# some code
# --- main ---
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
but these examples block program and it can't run other code.
To run other code you can put code before listener.join()
for keyboard
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
# ... your code ... (ie. mainloop in tkinter)
listener.join()
for mouse
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
# ... your code ... (ie. mainloop in tkinter)
listener.join()
Sometimes it can be easer to write the same code without with
for keyboard
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
#listener.wait()
# ... your code ... (ie. mainloop in tkinter)
listener.join()
for mouse
listener = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
listener.start()
#listener.wait()
# ... your code ... (ie. mainloop in tkinter)
listener.join()
This way you can use listener inside other functions or use as global variable.
You can even use both listeners at the same time
listener_keyboard = keyboard.Listener(on_press=on_press, on_release=on_release)
listener_keyboard.start()
#listener_keyboard.wait()
listener_mouse = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
listener_mouse.start()
#listener_mouse.wait()
# ... your code ... (ie. mainloop in tkinter)
listener_keyboard.join()
listener_mouse.join()
To stop both listeners you will have to use in some moment
listener_keyboard.stop()
listener_mouse.stop()
Listener runs code in thread
and this is why it uses functions .start()
and .join()
similar to module threading
.
Because Listener
runs code in thread
so there is no need to start it specially in another thread
.
