How to better control print and stdout?

Donn Cave donn at u.washington.edu
Fri Mar 14 18:40:56 EST 2003


Quoth Drew Smathers <drew.smathers at earthlink.net>:

| I'm new to python and have been having a hell of a time using stdout.
| Obviously Python has a unique way of printing strings.
...
| The program waits for the loop to end before printing anything.
| (If I omit the comma, this results in the program printing in sync
| with the loop but throws in the unwanted newline of course.) 

Not really that unique, you'd have the same problem in C for example,
or any programming language like Python that uses C stdio library
functions.  These functions buffer output according to various rules.
In your case, because you're writing to a "tty" device, you get "line
buffering" - the event that causes the buffer to be flushed to the
device is the "newline" character.  Just as soon as you send one, or
when the program exits, whichever happens first.

Or you can call sys.stdout.flush() after the print.  Or if this is
UNIX (or I guess even if it isn't) you can just use os.write(1, c),
which skips the pointless buffering.  Along those lines, you can
use sys.stdout.write(c) to avoid the pointless white space.

You could eliminate some of the repetition in the code, by the way -
for example, put the graphic characters in a list or string, index
that with the phase; reset phase to 0 when phase >= len(char list).

	Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list