autoflush on/off

Jabba Laci jabba.laci at gmail.com
Mon Feb 4 12:12:39 EST 2013


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?

Thanks,

Laszlo



More information about the Python-list mailing list