1

I was reading about std.flush() in python. And I found this example a lot.

import sys,time
for i in range(10):
    print i,
    #sys.stdout.flush() 
    time.sleep(1)

It is often said that it makes a difference with/without the "sys.stdout.flush()". However, when I called this script from command prompt, it didn't make a difference in my case. Both printed numbers to the screen in real time. I used python 2.7.5 in windows.

Why is that happening?

p.s. In another example which printed the output through subprocess.PIPE instead of to the screen directly, I did observe a difference of the buffering.

What am I missing?

enchy
  • 55
  • 3
  • There is likely an answer to explain what you're seeing, but... Is there a specific problem you're trying to solve, or is this intellectual curiosity? – dkamins Nov 24 '14 at 02:45
  • Your operating system is ultimately the one that will decide when to flush. Calling `flush` is simply a way to *guarantee* that the output buffer is flushed at that particular moment in time, but it may be flushed automatically by the OS even without calling `flush` explicitly. – tckmn Nov 24 '14 at 02:46
  • @dkamins You caught me.. It's out of curiosity, originally starting from a real problem that I somehow solved but didn't know how. And after some more reading and experimenting, here I am. – enchy Nov 24 '14 at 03:38
  • @Doorknob It looks more like an answer than a comment. :) BTW I am quite impressed by your profile. Cheers. – enchy Nov 24 '14 at 04:41

2 Answers2

2

Using flush will generally guarantee that flushing is done but assuming the reverse relationship is a logical fallacy, akin to:

  1. Dogs are animals.
  2. This is an animal.
  3. Therefore this is a dog.

In other words, not using flush does not guarantee flushing will not happen.

Interestingly enough, using Python 2.7.8 under Cygwin in Win81, I see the opposite behaviour - everything is batched up until the end. It may be different with Windows-native Python, it may also be different from within IDLE.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

See stdio buffering. In brief:

Default Buffering modes:

  • stdin is always buffered
  • stderr is always unbuffered
  • if stdout is a terminal then buffering is automatically set to line buffered, else it is set to buffered

For me, the example you gave prints:

In cmd:

  • all the numbers upon exit in Cygwin's python
  • one by one in Win32 python

In mintty:

  • both all upon exit
  • both one by one with -u option
  • sys.stdout.isatty() returns False!

So, it looks like msvcrt's stdout is unbuffered when it points to a terminal. A test with a simple C program shows the same behaviour.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • I didn't do anything to disable output buffering mentioned in the link. I was using python 2.7.5 and my streams point to the terminal (is it? I call it from the cmd window). – enchy Nov 24 '14 at 03:30