关于输出:Python tqdm并打印奇怪的打印输出顺序

Python tqdm and print weird printout order

本问题已经有最佳答案,请猛点这里访问。

我有以下Python 3代码:

1
2
3
4
5
from tqdm import tqdm

print("Before")
for _ in tqdm(range(10)): pass
print("After")

我希望将以下输出发送到终端:

1
2
3
Before
100%|##########| 10/10 [00:00<?, ?it/s]
After

但是,我得到的是:

1
2
3
100%|##########| 10/10 [00:00<?, ?it/s]
Before
After

即 相对于我的代码,打印输出的顺序错误。 我还尝试过在两次调用print之前和之后调用sys.flush,仅得到以下输出:

1
2
Before
100%|##########| 10/10 [00:00<?, ?it/s]After

同样,将print更改为tqdm.write对行为没有任何影响。

为什么它以这种意外的方式表现?

编辑:这个问题是关于在tqdm循环之前或之后使用打印功能的特定情况。 在tqdm循环中还有其他与打印消息有关的类似问题,此处并非如此。


默认情况下,tqdm打印到stderr。 对我来说,诀窍是将file=sys.stdout指定为tqdm以使其打印到与print相同的流,或者在调用print之前调用sys.stderr.flush