Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rewrite on several terminal lines in Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading