autoflush on/off

Terry Reedy tjreedy at udel.edu
Tue Feb 5 07:43:46 CET 2013


On 2/4/2013 7:09 PM, Jabba Laci wrote:
> 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

This could/should go in the __enter__ method. You do not need __init__ here.

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

This creates a new *python* object but perhaps it does something at the 
OS level that does not get reversed.

>      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)

from the time module :-?
> #
> 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

In 3.3, Win7, with the regular interpreter, I get
   File "<stdin>", line 5, in __enter__
   File "C:\Programs\Python33\lib\os.py", line 1032, in fdopen
     return io.open(fd, *args, **kwargs)
ValueError: can't have unbuffered text I/O

If I change the mode to 'wb', I get
   File "C:\Programs\Python33\lib\os.py", line 1032, in fdopen
     return io.open(fd, *args, **kwargs)
OSError: [Errno 9] Bad file descriptor

With IDLE, I get
   File "F:\Python\mypy\tem.py", line 7, in __enter__
     sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
AttributeError: fileno

It looks like you should perhaps just forget about reopening and just 
use sys.stdout.flush(). This works fine even on IDLE.

import sys, time

for i in range(10):
     sys.stdout.write('.'); sys.stdout.flush()
     time.sleep(.5)
 >>>
,,,,,,,,,,

Write a write_flush function if you want, and add any of the number, 
string, and sleep time as parameters if you wish.

-- 
Terry Jan Reedy




More information about the Python-list mailing list