1

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?

Finn
  • 2,333
  • 1
  • 10
  • 21

3 Answers3

0

You're trying to use ANSI escape sequences, which windows doesn't support, at least by default.

I've heard that you can use Colorama to enable these, once installed doing the following at the beginning of the program:

import colorama
colorama.init()
damaredayo
  • 1,048
  • 6
  • 19
0

@Tylerr answer works. However I just found out that if you have Win 10 after aniversary update (Version 1607, 02.08.2016 which probably most Win 10 users have by now) you can enable native support of the cmd.exe by adding or changing the VirtualTerminalLevel registry like shown here

Finn
  • 2,333
  • 1
  • 10
  • 21
0

I encountered this same problem today. I'm on Win10 Pro 1903.

I ended up downloading Windows Terminal and it fixed all of my problems! (https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701)

ANSI escape characters (like "\x1b[1A") now work!

Before on PowerShell: ANSI PowerShell fail

PS. Example from: Is there a way to clear your printed text in python?

But in Windows Terminal, it works!

Robert Lin
  • 369
  • 3
  • 9