4

If I run this code:

for x in range(10):
    time.sleep(1)
    print("a")

It will do exactly what it should. But if I run this:

for x in range(10):
    time.sleep(1)
    print("a", end="")

It will wait the entire 10 seconds and then print the 10 a's.

How can I prevent this?

Eric Urban
  • 3,671
  • 1
  • 18
  • 23
tkbx
  • 15,602
  • 32
  • 87
  • 122
  • 2
    Definitely not a library bug. Always assume your own code is at fault first (it's seen a lot less testing). The problem is that [`stdout` is line-buffered](http://www.pixelbeat.org/programming/stdio_buffering/). – Jonathon Reinhart Aug 02 '13 at 03:27
  • @JonathonReinhart that certainly seems logical, but this behavior seemed really eratic. Having to flush stdout certainly doesn't seem very "Python". They're probably very rare, but I have encountered bugs in the standard Python libraries before (zipfile in 2.6, apparently infamous) – tkbx Aug 02 '13 at 03:30

1 Answers1

8

Flush stdout after print.

import time
import sys

for x in range(10):
    time.sleep(1)
    print("a", end="")
    sys.stdout.flush()

Python 3.3 print function has optional flush parameter; You can write as follow in Python 3.3+.

import time

for x in range(10):
    time.sleep(1)
    print("a", end="", flush=True)
falsetru
  • 357,413
  • 63
  • 732
  • 636