GLHF
GLHF

Reputation: 4035

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")

Upvotes: 0

Views: 102

Answers (2)

linusg
linusg

Reputation: 6439

You may use ANSI escape characters for this:

sys.stdout.write("\033[F")  # Cursor up to line
sys.stdout.write("\033[K")  # Clear line

Or while this sometimes not works in Windows cmd, try this:

sys.stdout.write("\r")  # Move to line beginning

Or as you want it:

import time

print("Hello world", end="\r")
time.sleep(1)
print("New text   ")  # Trailing slashes to completely override "Hello world"

Upvotes: 2

Mike Müller
Mike Müller

Reputation: 85512

Flush the printed text, don't write a newline at the end but rather a \r in order to start printing at the beginning of the next line:

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

print ("Hello world", end='\r', flush=True)
time.sleep(1)
print ("New Text     ", end='\r', flush=True)
time.sleep(1)
print ("Last Text    ")

Upvotes: 0

Related Questions