Michael IV
Michael IV

Reputation: 11496

Clearing old data from sys.stdout in Python

There's something I don't get when writing to sys.stdout in Python.What I want is to write some strings into stdout without preprending the stuff which already has been written before that.

So doing this:

 while True:

    sys.stdout.write("k")
    sys.stdout.flush()

 sys.stdout.write("d")

After some "k" data has been written into stdout in a loop I need to write some new data afterwards,which is "d" for the sake of example. I am getting : "k d" in the output."K" from the loop writes is still in stdout.

What I want to get is just "d" .

Why? How can I clear the stdout before writing new data into it?

Btw,using print() instead still accumulates the old data into final output.

Using python 2.7 on Linux

Upvotes: 2

Views: 5355

Answers (2)

roippi
roippi

Reputation: 25974

Terminals don't work that way. flush just flushes the buffer (i.e. characters that may not have been printed to screen yet), it does not clear the screen.

If you want to erase one character, you need to print a literal backspace control character, and then print something over your previous output (like a space):

sys.stdout.write("\b ")

However. Your asking this belies a deep misunderstanding of how terminals work. Think of it like a text processor - there is text on the screen, and a cursor (which is invisible). You need to tell the cursor what to do to manipulate the text on the screen. Since the cursor is always in overwrite mode, a trick that is often useful is to go back to the start of the line:

 sys.stdout.write("\r")

and overwrite your data on that line. Note that if your new data is of lesser length than your previous data, this will leave some amount of previous data on the screen.

There are other tricks you can use if neither of these fits your bill, like outputting terminal control sequences to stdout.

(also, unless you have a specific need for using sys.stdout, just use print.)

Upvotes: 4

NPE
NPE

Reputation: 500713

I do have to print "k" but one line before "d".I want to print "d" in a completely new line.

Simply write a newline between the two:

sys.stdout.write("\n")

Or just use print, which adds an implicit newline at the end:

print "k"
print "d"

Upvotes: 0

Related Questions