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
  • 82,630
  • 20
  • 166
  • 161
GLHF
  • 3,835
  • 10
  • 38
  • 83
  • I think there are special characters to move the cursor in the cmd and delete specific parts – linusg Apr 23 '16 at 10:08
  • *a module replace New Text with Hello world* <- please be much more specific about this part. What exactly do you want to happen? Another python program should modify the program that prints out the message? – timgeb Apr 23 '16 at 10:13
  • Check out the curses module. – Alex Hall Apr 23 '16 at 10:13

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,289
  • 4
  • 28
  • 78
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
  • 82,630
  • 20
  • 166
  • 161