0

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")
Mike Müller
  • 77,540
  • 18
  • 155
  • 159
GLHF
  • 3,682
  • 9
  • 34
  • 79

2 Answers2

2

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"
linusg
  • 6,025
  • 4
  • 28
  • 70
0

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    ")
Mike Müller
  • 77,540
  • 18
  • 155
  • 159