'Python print end="\r" previous line not completely cleared
I want to replace current line in console
from time import sleep
print("loooooooooooooooooooog", end="\r")
sleep(1)
print("short", end="\r")
output
shortoooooooooooooooog
expected
short
Solution 1:[1]
for linux we can do
sys.stdout.write('\033[K Text \r')
# or
print('\033[K Text \r')
but it has strange result on windows powershell or cmd, so I use this function instead
from time import sleep
prevline = 0
def writeLine(text):
global prevline
current = len(text)
if current > prevline:
prevline = current
print(text.ljust(prevline), end="\r")
writeLine('looooooooooooong')
sleep(1)
writeLine('short')
sleep(1)
writeLine('s')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | uingtea |
