Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tqdm and print weird printout order [duplicate]

I have the following Python 3 code:

from tqdm import tqdm

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

I expect to get the following output to terminal:

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

However, what I get is this:

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

I.e. the printouts end up in the wrong order relative to my code. I have also tried calling sys.flush before and after both calls to print, only to get the following output:

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

Also, changing print to tqdm.write doesn't have any effect on the behavoir.

Why does it behave in this unexpected manner?

Edit: This question is about the specific case where the print function is used either before or after the tqdm loop. There are other, similar questions that are about printing messages while in the tqdm loop, which in not the case here.

like image 747
HelloGoodbye Avatar asked Jul 23 '17 10:07

HelloGoodbye


1 Answers

By default, tqdm prints to stderr. The trick for me was to either to specify file=sys.stdout to tqdm to make it print to the same stream as print, or to call sys.stderr.flush before calling print.

like image 73
HelloGoodbye Avatar answered Oct 31 '22 16:10

HelloGoodbye