Python3 sleep() problem

roddds picture roddds · Dec 16, 2010 · Viewed 22.7k times · Source

I was writing a simple program on Python 3.1 and I stumbled upon this:

If I run this on the IDLE it works as intended - prints "Initializing." and then adds two dots, one after each second, and waits for input.

from time import sleep

def initialize():
    print('Initializing.', end='')
    sleep(1)
    print(" .", end='')
    sleep(1)
    print(" .", end='')
    input()

initialize()

The problem is that when I double-click the .py to execute the file, it runs on python.exe instead of pythonw.exe, and strange things happen: it joins all the sleep() times i.e. makes me wait for 2 seconds, and then prints the whole string Initializing. . . at once. Why does this happen? Is there a way to avoid that happening in the terminal? It works fine if I use the IDLE in both windows and linux.

Answer

John La Rooy picture John La Rooy · Dec 16, 2010

This is because the output is being buffered.

You should add a sys.stdout.flush() after each write