JakeJLB
JakeJLB

Reputation: 29

Python 3.x - Strange behavior of the "end=" command in console?

Let's say I have this basic code:

import time

print("Thinking",end=" ")
for i in range(3):
    time.sleep(1)
    print(".",end=" ")
time.sleep(1)
print("I have the answer!")

Just given an example because copying over the whole thing is long, but on a basic level this is what I am trying to do. In the shell it works fine, it will print "thinking", wait a second, print a dot, wait another second, print another dot, and so on. However, in console, it waits 3 seconds then prints it all at once, why is this? I have figured out it must have something to do with the "end=" command, is there anything I can do to combat this but all the while being able to print stuff on the same line with time intervals? Thanks in advance.

Upvotes: 0

Views: 51

Answers (2)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19184

Since 3.3, the easier answer is to add flush=True to the print call.

print(".",end=" ", flush=True)

Upvotes: 1

Peter Sutton
Peter Sutton

Reputation: 1223

import sys and call sys.stdout.flush() after your call to print.

By default the stdout is line-buffered. Which means it caches writes internally until it sees a newline. Only when a newline is written does Python flush the file.

Upvotes: 0

Related Questions