本文介绍了Python:如何从线程函数中获取多个返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
调用了一个返回多个值的外部函数.
Have called an external function which returns multiple values.
def get_name(full_name):
# you code
return first_name, last_name
在简单的函数调用中,我可以得到结果.
In simple function call, I can get the results.
from names import get_name
first, last= get_name(full_name)
但我需要使用线程进行调用以获取第一个和最后一个变量的结果值.我未能使用简单的线程调用.
But I need to use threading for the call to get the result values for the first and last variables. I failed in using a simple threading call.
first, last= Threading.thread(get_name, args= (full_name,)
请帮我获取函数调用的返回值
Please help me to get the return values of the function call
推荐答案
你应该使用 queue
用于从线程中检索数据,这里有一个使用包装器将函数中的值存储到队列中的示例:
You should use a queue
for retrieve data from threads, here you have an example using a wrapper to store values from the functions into a queue:
import threading
import queue
my_queue = queue.Queue()
def storeInQueue(f):
def wrapper(*args):
my_queue.put(f(*args))
return wrapper
@storeInQueue
def get_name(full_name):
return full_name, full_name
t = threading.Thread(target=get_name, args = ("foo", ))
t.start()
my_data = my_queue.get()
print(my_data)
这里有实时工作示例
这篇关于Python:如何从线程函数中获取多个返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!