如何立即打印Python ThreadPoolExecutor.map的结果? [英] How to print results of Python ThreadPoolExecutor.map immediately?
本文介绍了如何立即打印Python ThreadPoolExecutor.map的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为几组可迭代对象运行一个函数,所有过程完成后立即返回所有结果的列表.
I am running a function for several sets of iterables, returning a list of all results as soon as all processes are finished.
def fct(variable1, variable2):
# do an operation that does not necessarily take the same amount of
# time for different input variables and yields result1 and result2
return result1, result2
variables1 = [1,2,3,4]
variables2 = [7,8,9,0]
with ThreadPoolExecutor(max_workers = 8) as executor:
future = executor.map(fct,variables1,variables2)
print '[%s]' % ', '.join(map(str, future))
>>> [ (12,3) , (13,4) , (14,5) , (15,6) ]
如何打印中间结果,例如对于变量1 = 1,变量2 = 7,一旦计算出结果?
How can I print intermediary results e.g. for variable1 = 1, variable2 = 7 as soon as their results are calculated?
推荐答案
map
已经做到了,但是join
需要消耗整个可迭代项才能创建连接的字符串.将其更改为for
循环将使您可以递增地打印它:
map
already does this, but join
needs to consume the entire iterable in order to create the joined string. Changing this to a for
loop will let you print it incrementally:
for i in executor.map(fct, v1, v2):
print(str(i))
保持与join
代码相同的输出还需要做更多的工作,但是无论如何:
Keeping the same output as the join
code is a bit more work, but doable regardless:
first = True
print("[ ", end="")
for i in executor.map(fct, v1, v2):
if first:
first = False
else:
print(" , ", end="")
print(str(i), end="")
print("]", end="")
这篇关于如何立即打印Python ThreadPoolExecutor.map的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文