【发布时间】:2018-05-27 11:24:35
【问题描述】:
通过下面的代码,我尝试使用ThreadPoolExecutor 在 jupyter 笔记本上并行打印一堆东西。请注意,使用函数show(),输出不是您通常期望的。
from concurrent.futures import ThreadPoolExecutor
import sys
items = ['A','B','C','D','E','F',
'G','H','I','J','K','L',
'M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z']
def show(name):
print(name, end=' ')
with ThreadPoolExecutor(10) as executor:
executor.map(show, items)
# This outputs
# AB C D E F G H I J KLMNOP QR STU VW XY Z
但是当我尝试使用 sys.stdout.write() 时,我没有得到这种行为。
def show2(name):
sys.stdout.write(name + ' ')
with ThreadPoolExecutor(10) as executor:
executor.map(show2, items)
# This gives
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
奇怪的是,我在 jupyter notebook 和编写 .py 文件并运行它都试过了。但是对于后者,我似乎没有遇到这个问题。我尝试搜索,但我得到的只是 python-3.x 中的print() 是 线程安全的。如果它确实是线程安全的,谁能解释为什么会这样?
【问题讨论】:
-
当您执行
print("%s "%(name), end ='')时会发生什么?end=变体可能会将名称和空格作为 distinct 操作输出,其中可能会在它们之间发生上下文切换。带有空格的单个字符串的print(以及一个空的end)可以缓解这种情况。 -
如果你使用的是 Python 3.3+,你可能想试试
print(..., flush=True')。
标签: python python-3.x jupyter-notebook jupyter