How to refresh multiple printed lines inplace using Python?
Question: I would like to understand how to reprint multiple lines in Python 3.5.

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

    
    
    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
    

What I am trying to do is have:

    
    
    Line 1
    Line 2
    Line 3
    Value = 1
    

Write on top of / update / refresh:

    
    
    Line 1
    Line 2
    Line 3
    Value = 0
    

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

I saw [another question from 5 years
ago](https://stackoverflow.com/questions/6840420/python-rewrite-multiple-
lines-in-the-console?noredirect=1&lq=1) however with the addition of the `end`
argument in Python 3+ print function, I am hoping that there is a much simpler
solution.


Answer: If I've understood correctly you're looking for this type of solution:

    
    
    import random
    import time
    import os
    
    
    def clear_screen():
        os.system('cls' if os.name == 'nt' else 'clear')
    
    a = 0
    while True:
        clear_screen()
    
        statement = """
        Line {}
        Line {}
        Line {}
        Value = {}
        """.format(random.random(), random.random(), random.random(), a)
        print(statement, end='\r')
        time.sleep(1)
        a += 1
    

This solution won't work with some software like IDLE, Sublime Text,
Eclipse... The problem with running it within this type of software is that
clear/cls uses ANSI escape sequences to clear the screen. These commands write
a string such as "\033[[80;j" to the output buffer. The native command prompt
is able to interpret this as a command to clear the screen but these pseudo-
terminals don't know how to interpret it, so they just end up printing small
square as if printing an unknown character.

If you're using this type of software, one hack around could be doing
print('\n' * 100), it won't be the optimal solution but it's better than
nothing.

