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

Python tqdm and print weird printout order

我有以下 Python 3 代码:

from tqdm import tqdm

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

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

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

然而,我得到的是:

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

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

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

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

为什么它会以这种意想不到的方式运行?

编辑: 这个问题是关于在 tqdm 循环之前或之后使用 print 函数的特定情况。还有其他类似的问题是关于在 tqdm 循环中打印消息,这里不是这种情况。

默认情况下,tqdm prints to stderr. The trick for me was to either to 使其打印到与 print 相同的流,或者在调用 print.

之前调用 sys.stderr.flush