12

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
roddds
  • 133
  • 1
  • 2
  • 6
  • 2
    I imagine the reason it's buffering is because you haven't given it a `\n` yet. In general the use of `end` will indicate you're going on and writing something immediately. – Chris Morgan Dec 16 '10 at 03:25

2 Answers2

24

This is because the output is being buffered.

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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 2
    And, after 4 years, I just noticed I never actually set this as an accepted answer. – roddds Aug 26 '14 at 03:05
  • 11
    Using Python 3's `print` function, you can also use the `flush` parameter, e.g. `print(" .", end='', flush=True)` – tobias_k Oct 19 '15 at 09:41
5

It sounds like the difference is that stdout is automatically being flushed in IDLE. For efficiency, programming languages often save up a bunch of print calls before writing to the screen, which is a slow process.

Here's another question that has the answer you need: How to flush output of Python print?

Community
  • 1
  • 1
leoger
  • 1,074
  • 10
  • 16