如何从 pynput.keyboard.Listener 线程获取 return 值?

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

我想获取 pynput.keyboard.Listener 中函数的 return 值。我认为它唯一可行的是使用全局变量。也 ThreadPool,但我认为它不会在 pynput 的这个预定义 threading.thread 中工作,调用 keyboard.Listener()

示例代码

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

如果你想避免使用 global variable.You 可以使用 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)