autoflush on/off

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Mon Feb 4 13:24:28 EST 2013


Am 04.02.2013 18:12, schrieb Jabba Laci:
> 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

Note that you have two file objects (one not reachable any more) both 
writing to the same file descriptor. This also means you should first 
flush sys.stdout before changing it, otherwise it might still contain 
unflushed data.

> 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?

Just set sys.stdout back to the original value. OTOH, also check if you 
can't tell sys.stdout not to buffer.

> As far as I remember, in Perl it was simply $| = 1 and $| = 0.

"simply" ... ;)


Uli




More information about the Python-list mailing list