autoflush on/off

J

Jabba Laci

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
 
U

Ulrich Eckhardt

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
 
G

garabik-news-2005-05

Jabba Laci said:
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.

My solution is sys.stdout.write('.'); sys.stdout.flush()
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top