autoflush on/off

Piet van Oostrum piet at
Tue Feb 5 12:59:55 CET 2013

Ulrich Eckhardt <ulrich.eckhardt at> writes:

> Am 05.02.2013 01:09, schrieb Jabba Laci:

>> setting the sys.stdout back to the original value doesn't work.
> [...]
>> The problem is in __exit__ when sys.stdout is pointed to the old
>> value. sys.stdout.write doesn't work from then on. Output:
>> .....close failed in file object destructor:
>> sys.excepthook is missing
>> lost sys.stderr
> Argh! Yes, the newly-created file object takes ownership of the
> filedescriptor. Once done with it, it invokes close() on it, making it
> unusable for the original sys.stdout.

That can be solved with a dup.

import os, sys

class Unbuff(object):
    def __enter__(self):
        self.stdout_bak = sys.stdout
        sys.stdout = os.fdopen(os.dup(sys.stdout.fileno()), 'w', 0)

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout = self.stdout_bak

Piet van Oostrum <piet at>
PGP key: [8DAE142BE17999C4]

More information about the Python-list mailing list