What does sys.stdout.flush() do?

Peter Otten __peter__ at web.de
Fri Aug 23 08:21:16 EDT 2013


D. Xenakis wrote:

> Somewhere i read..
> sys.stdout.flush(): Flush on a file object pushes out all the data that
> has been buffered to that point.
> 
> Can someone post here a script example with sys.stdout.flush(), where in
> case i commented that i could understand what the difference really would
> be?
> 
> Whenever i try to remove that line (in scripts that i find online), i cant
> find any differences. I've just noticed that it is usually called right
> after sys.stdout.write(..) thx

Use time.sleep() to see the effects of (line) buffering. Type the following 
in your interactive interpreter and be enlightened ;)

>>> import sys, time
>>> for i in range(10):
...     print i,
...     time.sleep(.1)
... 
0 1 2 3 4 5 6 7 8 9
>>> for i in range(10):
...     print i,
...     sys.stdout.flush()
...     time.sleep(.1)
... 
0 1 2 3 4 5 6 7 8 9





More information about the Python-list mailing list