"print" strange with Sybase module

Erwin S. Andreasen erwin at andreasen.com
Sun Jan 28 09:04:53 EST 2001


On Sun, 28 Jan 2001 01:09:59 -0500, Chris wrote:

>I've been experiencing this unflushed buffer issue as well when running some
>Python programs in the background and redirecting their output to log files.
>Is there any way that I could force the buffers to flush somehow?  I am
>being plagued by incomplete log files!  Or perhaps there is a better
>approach?

You can run Python with the -u switch -- that will force stdin/out/err etc. to
be completely unbuffered.

Or use sys.stdout.flush() to ensure that stdout is flushed whenever you have
written something important (Assuming that you already have a log function
that prints stuff like timestamp, so you could put it there).

AFAICS, there is no way to turn the buffering to be line-based on an existing
file object (it might be an idea for a future release?). You could do
something like:

sys.stdout = os.fdopen(os.dup(sys.stdout.fileno()), 'w', 1)

which would reopen standard output as a line-buffered (the 1) stream,
i.e. every time you have written a full line to the file object, it's flushed
-- just like when you run the program on the console.

(they os.dup may not be strictly necessary in case of sys.stdout -- but if you
have another file object and do the above to it, it would get destroyed, which
also means that its underlying unix file descriptor would get closed. So you'd
have a new file object that has a closed file descriptor).

Oh -- I'm not sure if os.dup and os.fdopen work under non-UNIX systems.

-- 
=======================================================================
<erwin at andreasen.com>           Herlev, Denmark       Software Designer
<URL:http://www.andreasen.org/>       <*>         LASAT^WEicon Networks
=======================================================================



More information about the Python-list mailing list