Search code examples
pythonpython-2.7stdoutflushsys

Python - sys.stdout.flush() on 2 lines in python 2.7


I am writing with python 2.7

I have the following code:

a = 0
b = 0
while True:
    a += 1
    b += 1
    print str(a)
    print str(b)

The output looks like:

1
1
2
2
3
3
4
....

And want to flush these two lines with stdout.flush(). The code looks like this but it's not working..

import sys

a = 0
b = 0
while True:
    a += 1
    b += 1
    sys.stdout.write(str(a)+"\n")
    sys.stdout.write(str(b)+"\r")
    sys.stdout.flush()

And this produces an output like this:

1   #1
2   #1   ->#2
3          #2   ->#3
4                 #3   ->#4
...

I know this is because \r only jump to the beginning of the 2nd line, and start from the the next prints..

How can I set the cursor to the beginning of 1st line instead of the 2nd line?

So that it will refresh only 2 lines:

n  #1 ->#2  ->#3  ->#4  ->#.....
n  #1 ->#2  ->#3  ->#4  ->#.....

I hope somebody will understand what I mean.


Solution

  • to go to the upper line from the current one this has to be written on the stdout \x1b[1A

    CURSOR_UP_ONE = '\x1b[1A' 
    

    to erase the contents of the line \x1b[2K has to be written on stdout.

    ERASE_LINE = '\x1b[2K'
    

    this way you could go to the upper line and overwrite the data there.

    data_on_first_line = CURSOR_UP_ONE + ERASE_LINE + "abc\n"
    sys.stdout.write(data_on_first_line)
    
    data_on_second_line = "def\r"
    sys.stdout.write(data_on_second_line)
    sys.stdout.flush()
    

    for more details http://www.termsys.demon.co.uk/vtansi.htm#cursor

    and https://stackoverflow.com/a/12586667