1

let me describe exactly what I'm asking. suppose that python console looks like this:

line1
line2
line3
line4
line5
...

now suppose you have a loop that prints into 3 lines with every iteration. so usually it would print into line1, line2 and line3 in the first iteration, then 4,5,6 in second and so on. I want to make it print ONLY into line1, 2 and 3, while deleting what was previously in those lines.

reason for this is I have a lot to print and what was printed before doesn't matter anymore, so this way I wouldn't create a huge number of lines.

EDIT: I think it's not a duplicate question since there are more lines in question here. I think clearing the entire console is the simplest solution here. Thanks for your answers!

DoctorEvil
  • 453
  • 3
  • 6
  • 18
  • 7
    Possible duplicate of [Replace console output in Python](https://stackoverflow.com/questions/6169217/replace-console-output-in-python) – custom_user Jun 22 '17 at 09:14
  • Could clear the console every time the iteration happens. Thus cleaning the screen of the previous prints and making a blank slate ready for the next iteration – Goralight Jun 22 '17 at 09:14
  • You could clear the console with every iteration, provided you mean you are printing to the console. This may be of use `os.system('cls')` – PeskyPotato Jun 22 '17 at 09:15

3 Answers3

1

The best way to achieve this is to use termcap (terminal capabilities)

The curses module has what you need: https://docs.python.org/3.5/library/curses.html#module-curses

Or you can do it in a more hacky way by printing control characters and sequences directly as suggested in the other answer.

https://en.wikipedia.org/wiki/ANSI_escape_code

Maresh
  • 4,644
  • 25
  • 30
0

Add a "\r" first to replace the last line. There shouldn't be any newline inbetween.

Python2:

>>> print("line1"),;print("\rline2")
line2 

Python3:

>>> print("line1", end="");print("\rline2")
line2

"line1" has been overwritten by "\rline2".

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

You can do it using ANSI escape code "\033[F", that should work in many terminals:

import time

lines = ['line %d' % n for n in range(10)]

reset_after = 3

for number, line in enumerate(lines):
    if number > 0 and not number % reset_after:
        # if we wrote n lines, we are now on line n+1,
        # so we go up n+1 lines
        print("\033[F" * (reset_after + 1))
    # We must first erase the line where we're about to write,
    # in case our new line is shorter. 
    # "\033[K" erases from the cursor
    print("\033[K" + line)
    time.sleep(0.5)

That works perfectly in my Linux terminal.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50