Using Python 3.7, I am trying to rewrite multiple lines of output in the command window (Windows 10 - cmd). For a single line its easy, as i can just print the line again using carriage return.
print('\r only once',end='')
print('\r only once',end='')
However this won't work if there are multiple lines. Now i tried to do this using ascii control charachters. This is usually done in a loop to show the progress, but a minimal example is
import os
import sys
import time
print("upper") #moves back in line
print("lower") #moves back in line
#time.sleep(1)
#os.system("pause")
sys.stdout.write("\033[K") #clear line
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
sys.stdout.write("\033[F") #back to previous line
print("new upper") #moves back in line
print("new lower") #moves back in line
If it runs like this or with time.sleep(1)
uncommented the output is:
upper
lower
[K[F[K[F[K[Fnew upper
new lower
If os.system("pause")
(windows only) is uncommented the output is correct
new upper
new upper
Does anyone know, why os.system("pause")
changes the behavior of the control characters or how to enable them in general? Alternatively, does anyone has an other (or maybe even better) idea on how to replace multiline output from python?