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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With