how do i disable buffered output, like Perl's '$|=1'?

David Bolen db3l at fitlinxx.com
Mon Jan 15 19:04:13 EST 2001


"floR" <flor_pino at hotmail.com> writes:

> I can't find anywhere how I can disable 'buffered output', or whatever it is
> called.
> In Perl, you simply say $|=1, but in Python?
> Can anyone help me?

I'm not aware of any built-in way to permanently disable buffering
from within a script, although you can of course flush a file object
when appropriate.  However, you can also pretty easily wrap sys.stdout
(or any file object you are using) with an auto-flushing class, for
example:

    class FlushFile:

	def __init__ (self, file):
	    self.file = file

	def write(self, data):
	    self.file.write(data)
	    self.file.flush()

	def __getattr__(self, attr):
	    return getattr(self.file,attr)

If you were controlling flushing of your own files you could:

    file = FlushFile(open('filename','w'))

or just pass in any file handle that you have gotten from elsewhere in
your script.  Or for standard output, something like:

    sys.stdout = FlushFile(old_stdout)

(Note that in the latter case you should save sys.stdout for later
 restoration, and don't use it for output - say for debugging - in the
 write() method or you'll infinitely recurse)

After this, any references to that file will include autoflushing (not
necessarily at the byte by byte level, but following any output call).

In addition, and unlike Perl, you can control the buffering of Python
externally to the script.  For me, this has actually be more
convenient, since I normally want buffering control when I'm wrapping
an existing script into some other process, and would rather not have
to edit the script.

You can either use the "-u" command line option or set a
PYTHONUNBUFFERED environment variable to disable all buffering for any
scripts run by an interpreter that has that setting.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list