autoflush on/off

Terry Reedy tjreedy at udel.edu
Mon Feb 4 16:13:50 EST 2013


On 2/4/2013 12:12 PM, Jabba Laci wrote:
> Hi,
>
> I'd like to set autoflush on/off in my script. I have a loop that is
> checking something and every 5 second I want to print a '.' (dot). I
> do it with sys.stdout.write and since there is no newline, it is
> buffered and not visible immediately. I have this solution to use
> unbuffered output:
>
> autoflush_on = False
>
> def unbuffered():
>      """Switch autoflush on."""
>      global autoflush_on
>      # reopen stdout file descriptor with write mode
>      # and 0 as the buffer size (unbuffered)
>      if not autoflush_on:
>          sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
>          autoflush_on = True
>
> I call unbuffered() once and it works well. However, when this loop is
> over, I'd like to set the output back to buffered. How to do that? As
> far as I remember, in Perl it was simply $| = 1 and $| = 0. Can it
> also be switched back and forth in Python?

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




More information about the Python-list mailing list