autoflush on/off

Jabba Laci jabba.laci at gmail.com
Tue Feb 5 01:09:48 CET 2013


Hi,

Thanks for the answers. I like the context manager idea but setting
the sys.stdout back to the original value doesn't work.

Example:

class Unbuff(object):
    def __init__(self):
        self.stdout_bak = sys.stdout

    def __enter__(self):
        sys.stdout.flush()
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

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

####

with Unbuff():
        for i in range(5):
            sys.stdout.write('.')
            sleep(.5)
#
sys.stdout.write('EXIT')    # provokes an error


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

Laszlo


> Write a context manager class. See Library manual, 4.11. Context Manager
> Types. The __enter__ method would be much like the above except that is
> should save the old stdout object 'oldstdout = sys.stdout' instead of
> fiddling with 'autoflush_on'. Then __exit__ would simply be 'sys.stdout =
> oldstdout'. Drop autoflush_on.  Your context manager should not care about
> the existing buffering other than to restore it on exit. Saving and
> restoring the existing stdout object does that.
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list