Search code examples
pythonmultithreadingreturnthreadpoolpynput

How to get the return value from pynput.keyboard.Listener Thread?


I would like to get the return value of a function within pynput.keyboard.Listener. The only thing I thought it could work was using global variables. Also ThreadPool, but I think it will not work in this predefine threading.thread from pynput called keyboard.Listener()

SAMPLE CODE

message = ' '
keys = []

def write_keys(keys):
    global message
    for key in keys:
        k = str(key).replace(f'{chr(39)}', '')
        print(k)
        message += k
    if len(message) == 10:
        return message # return this value

def on_press(key):
    global keys
    keys.append(key)
    write_keys(keys)
    keys = []

keyboard_thread = keyboard.Listener(on_press=on_press)
keyboard_thread.start()
#messages = return the message value

Solution

  • If you want to avoid using global variable.You could use ThreadQueue.

    from pynput import keyboard
    from queue import Queue
    
    message = ''
    keys = []
    
    queue = Queue()
    
    def write_keys(keys):
        global message
        for key in keys:
            k = str(key).replace(f'{chr(39)}', '')
            print(k)
            message += k
        if len(message) == 10:
            queue.put(message)
    
    def on_press(key):
        global keys
        keys.append(key)
        write_keys(keys)
        keys = []
    
    keyboard_thread = keyboard.Listener(on_press=on_press)
    keyboard_thread.start()
    while True:
        messages = queue.get()
        print(messages)