GLHF GLHF - 7 months ago 9
Python Question

How to clean a specific thing on command line

I'm wondering is that possible to clean a specific thing on command shell run by a Python script?

E.g a script contains:

print ("Hello world")


When I double click on this script, cmd will pop up and I'll see
Hello world
on command line. Now I'm wondering, is that possible to clean
Hello World
from shell and write something else on there while cmd is running? Like:

print ("Hello world")
time.sleep(1)

# a module replace New Text with Hello world
print("New Text")

Answer

Flush the printed text, don't write a newline at the end, and start printing at the beginning of the line with \r would work:

from __future__ import print_function  # to make it work with Python 2, just in case
import time

print ("Hello world", end='', flush=True)
time.sleep(1)
print ("\rNew Text     ", end='', flush=True)
time.sleep(1)
print ("\rLast Text    ")
Comments