There seems to be a difference in how stdout
is buffered on Windows and on Linux when written to console. Consider this small python script:
import time
for i in xrange(10):
time.sleep(1)
print "Working" ,
When running this script on Windows we see Working
s appearing one after another with a second-long wait in-between. On Linux we have to wait for 10 seconds and then the whole line appears at once.
If we change the last line to print "Working"
, every line appears individually on Linux as well.
So on Linux, stdout
seems to be line-buffered and on Windows not at all. We can switch off the buffering by using the -u
-option (in this case the script on Linux has the same behavior as on Windows). The documentation says:
-u Force stdin, stdout and stderr to be totally unbuffered.
So actually, it does not say, that without -u
-option stdin
and stdout
are buffered. And thus my questions:
- What is the reason for different behavior on Linux/Windows?
- Is there some kind of guarantee, that if redirected to a file,
stdout
will be buffered, no matter which OS? At least this seems to be the case with Windows and Linux.
My main concern is not (as some answers assume) when the information is flushed, but that if stdout
isn't buffered it might be a severe performance hit and one should not rely on it.
Edit: It might be worth noting, that for Python3 the behavior is equal for Linux and Windows (but it is not really surprising, because the behavior is configured explicitly by parameters of the print
-method).