How to refresh multiple printed lines inplace using Python?
<p>I would like to understand how to reprint multiple lines in Python 3.5.</p>

<p>This is an example of a script where I would like to refresh the printed statement in place.</p>

<pre><code>import random
import time

a = 0
while True:
    statement = """
    Line {}
    Line {}
    Line {}
    Value = {}
    """.format(random.random(), random.random(), random.random(), a)
    print(statement, end='\r')
    time.sleep(1)
    a += 1
</code></pre>

<p>What I am trying to do is have:</p>

<pre><code>Line 1
Line 2
Line 3
Value = 1
</code></pre>

<p>Write on top of / update / refresh:</p>

<pre><code>Line 1
Line 2
Line 3
Value = 0
</code></pre>

<p>The values of each line will change each time. This is effectively giving me a status update of each Line.</p>

<p>I saw <a href="https://stackoverflow.com/questions/6840420/python-rewrite-multiple-lines-in-the-console?noredirect=1&amp;lq=1">another question from 5 years ago</a> however with the addition of the <code>end</code> argument in Python 3+ print function, I am hoping that there is a much simpler solution.</p>

<p>You could use <a href="https://docs.python.org/3/library/curses.html?highlight=ncurses" rel="nofollow">curses</a> for this.</p>

<pre><code>#!/usr/bin/python3

import curses
from time import sleep
from random import random

statement = """
Line {}
Line {}
Line {}
Value = {}"""

screen = curses.initscr()
n = 0

while n &lt; 20:
    screen.clear()
    screen.addstr(0, 0, statement.format(random(), random(), random(), n))
    screen.refresh()
    n += 1
    sleep(0.5)

curses.endwin()
</code></pre>

python python-3.x printing stdout