difference in printing to screen Mac / Windows
Tim Chase
python.list at tim.thechases.com
Sat Jul 18 07:03:11 EDT 2009
> I notice a difference between running the following script on my Mac and on
> a PC:
>
> from time import sleep
> for i in range(10):
> print i,
> sleep(2)
>
> On my PC this prints a number every 2 seconds. This is the behavior I want.
>
> On my Mac Python waits 10*2 = 20 seconds, and then prints 0 1 2 3 4 5 6 7 8
> 9
This sounds like a buffered vs. non-buffered output issue. My
guess would be that if you increased 10 to something larger, the
output buffer would flush at various intervals. The solution on
the Mac (or other *nix-like OSes) would be to either start python
in unbuffered mode:
python -u mycode.py
Alternatively, you can force a flush of the output buffer at each
iteration:
import sys
for i in range(10):
print i
sys.stdout.flush()
sleep(2)
Lastly, you can force all standard-output in your program to be
unbuffered without the "-u" parameter:
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Hope this helps,
-tkc
More information about the Python-list
mailing list