user3528254
user3528254

Reputation: 105

Stdout and flush? It's appending and not flushing

What I'm trying to do is have some 'progress text' on the bottom of a script that I've creating. If I for loop a list [1,2,3,4,5] and print i, then it simply prints 1,2,3,4, and 5 on separate lines. How about if I want to print 1 out to the screen, sleep 5 seconds, clear that out and then print 2?

I've tried using stdout.write("text"), sleep, flush, stdout.write("aetlkjetjer"), sleep, and it just simply adds on to that "text" statement instead of flushing the output.

Am I misunderstanding something with the way stdout.flush works? Isn't it supposed to flush/erase the output of the previous print?

Upvotes: 1

Views: 543

Answers (2)

NightShadeQueen
NightShadeQueen

Reputation: 3334

All .flush() does is flush out the buffer. What you actually want is to write backspace(\b) to stdout.

import time, sys

for i in [1,2,3,4,5]:
    sys.stdout.write(str(i))
    sys.stdout.flush() #flush the buffer because python buffers stdout
    time.sleep(5)
    sys.stdout.write("\b") #literally "write backspace".
    sys.stdout.flush()

It gets more complicated if you want to count up to numbers with more than one digit.

Upvotes: 3

Sam Estep
Sam Estep

Reputation: 13294

In computer science, the term "flush" doesn't mean to erase what's already in a buffer; rather, it means to take the unwritten contents of a buffer in memory (like the stdout buffer) and write it, in this case to the screen. So when you tell the program to "flush stdout", you're really just telling it to "take what's in stdout and make sure it's all displayed on the screen."

Upvotes: 3

Related Questions