0

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.

JakeJLB
  • 29
  • 1
  • This was discussed in https://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print, although I suspect you did not know to search for 'flush'. – Terry Jan Reedy Mar 03 '15 at 03:58

2 Answers2

1

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

print(".",end=" ", flush=True)
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
0

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.

Peter Sutton
  • 1,145
  • 7
  • 20