8

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.

HelloGoodbye
  • 3,624
  • 8
  • 42
  • 57
  • 1
    @zwer I wouldn't say this is necessarily a duplicate as that question is about printing while still in a tqdm loop. But one of the answers to that question provided me with a solution, so thanks! :) – HelloGoodbye Jul 23 '17 at 13:26
  • 1
    @zwer I believe this question has been marked incorrectly as an exact duplicate of the other question – they are different as I explained in an edit to the question. How do I unmark it as an exact duplicate? – HelloGoodbye Jul 23 '17 at 15:53

1 Answers1

10

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.

HelloGoodbye
  • 3,624
  • 8
  • 42
  • 57