如何在python中从多处理中获得函数输出



我有两个函数,需要返回值来继续脚本的下一部分。。。但目前我的代码只给出了第一个函数的输出。。。

import multiprocessing
def gm(name):
h = "Good Morning"+str(name)
qout.put(h)
def sal(name):
k="Hi "+str(name)
qout.put(k)
if __name__ == '__main__':
qout = multiprocessing.Queue()
p1 = multiprocessing.Process(target=gm, args=("ashin",))
p2 = multiprocessing.Process(target=sal, args=("ashin",))
p1.start()
p2.start()
p1.join()
p2.join()
result = qout.get()

#输出-";早上好;

#所需输出-";早上好"嗨,阿信">

感谢你的帮助。。。。。。

qout.get((从队列中获取第一个元素。我不知道您要实现的目标的全貌,但您可以从队列中获得所有元素,如下所示。

from multiprocessing import Process, Queue
def gm(name):
h = "Good Morning"+str(name)
qout.put(h)
def sal(name):
k="Hi "+str(name)
qout.put(k)
if __name__ == '__main__':
qout = Queue()
p1 = Process(target=gm, args=("ashin",))
p2 = Process(target=sal, args=("ashin",))
p1.start()
p2.start()
p1.join()
p2.join()
list1 = []
while not qout.empty():
list1.append(qout.get())
temp = list(map(str, list1))
print(" & ".join(temp))

输出

Hi ashin & Good Morningashin

不用管理自己的输出队列,只需使用最新的Python 3并发功能:

from concurrent.futures import as_completed, ProcessPoolExecutor
def gm(name):
return f'Good Morning {name}'
def sal(name):
return f'Hi {name}'
if __name__ == '__main__':
with ProcessPoolExecutor() as exe:
futures = [exe.submit(x, 'ashin') for x in (gm, sal)]
for future in as_completed(futures):
print(future.result())

相关内容

  • 没有找到相关文章

最新更新