Search code examples
pythonmultithreadingkeyboardterminatepynput

How to run pynput in the background?


I am using pynput's keyboard.Listener and have joined the thread.

def main():
    with Listener(on_release=checkSPress) as listener:
        listener.join() # keep on listening

def checkSPress(key):
    if 'char' in dir(key):
        if key.char == 's':
            print("Starting ...")

main()

After the s key is pressed I want it to terminate the listener and run things in the main thread. I want to this because after the s key is pressed I create a GUI but it throws an error that the QApplication must be created inside main thread. Is there a way I can go back to the main thread and run the function or terminate the listener entirely (I'm fairly new to threading and pynput.)


Solution

  • You just need to return False from callback to stop Listner. Just try:

    if key.char == 's':
        print("Starting ...")
        return False