0

I'm trying to rewrite on two lines on my terminal from a Python3 script.
Let's take a quick example:

import time

for n in range(1, 10):
    print(n)
    print(n*2)
    time.sleep(1)

When i launch my script I'd like to have this output :

bla@bla:/tmp$ python3 test.py
1
2

Then a second later (after the sleep) I want the 2 numbers to be "replaced by the new output" like this :

bla@bla:/tmp$ python3 test.py
2
4

and so on...

What have I tested ?

  • I've tried to put os.system("clear") at the begining of my for loop, but it's pretty uggly and it doesn't do what I want...
  • I've tried to put end '\r' at the end of my print as suggested here
  • I've tried to launch this commands with os.system() but it didn't work

Do you have any solutions ? Thanks for your help.

1 Answers1

1

It'll depend on the terminal emulator you use, but you probably want the ANSI 'cursor up' codes to be output, which will move the cursor up ready for the next iteration. The code you want is "ESCAPE [ A"

import time

for n in range(1, 10):
    print(n)
    print(n*2)
    time.sleep(1)
    print("\033[A\033[A", end="")

An ESCAPE is character 27, which is 033 in octal. Note the end="" to stop the cursor moving down again...

Thickycat
  • 894
  • 6
  • 12