Re: autoflush on/off

Discussion in 'Python' started by Terry Reedy, Feb 4, 2013.

  1. Terry Reedy

    Terry Reedy Guest

    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
     
    Terry Reedy, Feb 4, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Herman Chan

    CGI autoflush in Window

    Herman Chan, Oct 9, 2003, in forum: Perl
    Replies:
    0
    Views:
    581
    Herman Chan
    Oct 9, 2003
  2. Jabba Laci

    autoflush on/off

    Jabba Laci, Feb 4, 2013, in forum: Python
    Replies:
    2
    Views:
    105
  3. Jabba Laci

    Re: autoflush on/off

    Jabba Laci, Feb 5, 2013, in forum: Python
    Replies:
    2
    Views:
    132
    Piet van Oostrum
    Feb 5, 2013
  4. Terry Reedy

    Re: autoflush on/off

    Terry Reedy, Feb 5, 2013, in forum: Python
    Replies:
    0
    Views:
    133
    Terry Reedy
    Feb 5, 2013
  5. Lele Gaifax

    Re: autoflush on/off

    Lele Gaifax, Feb 5, 2013, in forum: Python
    Replies:
    0
    Views:
    101
    Lele Gaifax
    Feb 5, 2013
Loading...

Share This Page