Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: autoflush on/off

Thread Tools

Re: autoflush on/off

Terry Reedy
Posts: n/a
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\", line 1032, in fdopen
return, *args, **kwargs)
ValueError: can't have unbuffered text I/O

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

With IDLE, I get
File "F:\Python\mypy\", 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()


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

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem with autoflush on Semaphore-threads for Windows dede Perl 0 07-28-2004 03:48 PM
Autoflush in python cgi Gianluca Trombetta Python 1 06-02-2004 01:13 AM
Autoflush for DB_FILE to share a hash among cooperating processes? Axel Boldt Perl Misc 1 04-07-2004 03:33 PM
Yet Another Autoflush problem -- What's wrong with this code? John Chambers Perl Misc 2 01-23-2004 08:54 PM
CGI autoflush in Window Herman Chan Perl 0 10-09-2003 05:08 PM