[Python-3000] print() flushing problem.

Guido van Rossum guido at python.org
Wed Nov 7 16:32:37 CET 2007


On Nov 7, 2007 6:10 AM, Daniel Stutzbach
<daniel at stutzbachenterprises.com> wrote:
> On Nov 7, 2007 6:59 AM, Wojciech Walczak
> <wojtek.gminick.walczak at gmail.com> wrote:
> > py3k's print() is not flushing when end is set to '' and all it has to
> > print is one-character-long string:

print() should never flush. The stream can be set to flush when a
newline is seen (set buffer size to 1) though there may currently be
some bugs in that code. Interactive mode should flush before printing
the >>>prompt.

> print() shouldn't flush if there isn't a newline, unless the buffer is
> full or the user calls flush().  However, in an interactive
> interpreter in pre-3.0, Python will automatically add a newline.  Try
> this in 2.5:
>
> ---------------------------------------
> import time
> print 'foo',
> time.sleep(10)
> print
> ---------------------------------------
>
> You'll see that "foo" appears *after* 10 seconds, not before.
> However, in an interactive interpreter, Python will add a newline
> after 'foo' ever with the comma there, and the newline causes a flush.
>  Observe (2.5):
>
> >>> print 'foo',
> foo
> >>> print 'foo'
> foo
> >>>
>
> The same number of newlines are created with the comma and without,
> which is different than the script behavior.

Right. This is because 2.x doesn't only flush, it also adds a newline
when the last character written wasn't a newline.

> It sounds like P3K isn't doing this.

That's because it doesn't have the 'softspace' feature used by 2.x to
implement the automatic appending of a newline as needed. The
softspace feature was intentionally removed because it is a royal pain
to deal with.

Adding the flush back to interactive mode should be easy (flush both
stdout and stderr). Adding the auto-newline back is not; I'm not
convinced that it is necessary to do so since it'll be pretty rare and
usually the user is asking for trouble.

> The patch you suggest would cause a flush after *every* write with
> print, which would cause a very significant performance hit on
> programs that do a lot of writing to standard output (especially if
> standard output is a pipe).

Right, don't do that!

> Tangent: If standard output is a pipe and not a tty, is P3K smart
> enough to switch to fully-buffered mode instead of line-buffered mode?

It checks isatty() when the buffer size is not given explicitly, so it
should be. Worth testing though.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list