Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: difference in printing to screen Mac / Windows

0 views
Skip to first unread message

Tim Chase

unread,
Jul 18, 2009, 7:03:11 AM7/18/09
to Mark Bakker, pytho...@python.org
> 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


ryles

unread,
Jul 24, 2009, 11:22:55 AM7/24/09
to
On Jul 18, 7:03 am, Tim Chase <python.l...@tim.thechases.com> wrote:
> Lastly, you can force all standard-output in your program to be
> unbuffered without the "-u" parameter:

And if you're using -u a lot, the PYTHONUNBUFFERED environment
variable can also be set (but not empty), so that python adds the
option automatically.

0 new messages