Python - sys.stdout.flush() on 2 lines in python 2.7
<p>I am writing with python 2.7</p>

<p>I have the following code:</p>

<pre><code>a = 0
b = 0
while True:
    a += 1
    b += 1
    print str(a)
    print str(b)
</code></pre>

<p>The output looks like:</p>

<pre><code>1
1
2
2
3
3
4
....
</code></pre>

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

<pre><code>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()
</code></pre>

<p>And this produces an output like this:</p>

<pre><code>1   #1
2   #1   -&gt;#2
3          #2   -&gt;#3
4                 #3   -&gt;#4
...
</code></pre>

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

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

<p>So that it will refresh only 2 lines:</p>

<pre><code>n  #1 -&gt;#2  -&gt;#3  -&gt;#4  -&gt;#.....
n  #1 -&gt;#2  -&gt;#3  -&gt;#4  -&gt;#.....
</code></pre>

<p>I hope somebody will understand what I mean.</p>

<p>to go to the upper line from the current one this has to be written on the stdout <code>\x1b[1A</code></p>

<pre><code>CURSOR_UP_ONE = '\x1b[1A' 
</code></pre>

<p>to erase the contents of the line <code>\x1b[2K</code> has to be written on stdout.</p>

<pre><code>ERASE_LINE = '\x1b[2K'
</code></pre>

<p>this way you could go to the upper line and overwrite the data there.</p>

<pre><code>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()
</code></pre>

<p>for more details <a href="http://www.termsys.demon.co.uk/vtansi.htm#cursor" rel="nofollow">http://www.termsys.demon.co.uk/vtansi.htm#cursor</a></p>

<p>and <a href="http://stackoverflow.com/a/12586667">http://stackoverflow.com/a/12586667</a></p>

python python-2.7 stdout flush sys