Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38141 > unrolled thread

Re: autoflush on/off

Started byTerry Reedy <tjreedy@udel.edu>
First post2013-02-04 16:13 -0500
Last post2013-02-04 16:13 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: autoflush on/off Terry Reedy <tjreedy@udel.edu> - 2013-02-04 16:13 -0500

#38141 — Re: autoflush on/off

FromTerry Reedy <tjreedy@udel.edu>
Date2013-02-04 16:13 -0500
SubjectRe: autoflush on/off
Message-ID<mailman.1334.1360012468.2939.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web