I know this is an old question and you've probably found the solution, but it never hurts to help future viewers that have the same question. I see that you've commented on the answer marked correct asking if you could erase multiple lines at once. The way I would approach this is like so:
import sys
import time
def go_to_start(text):
lines = text.split('\n') # separate lines
nlines = len(lines) # number of lines
sys.stdout.write('\x1b[%sA' % (nlines - 1)) # move up to first line
sys.stdout.write('\r') # move to beginning of line
text = '''
this is my
multiline text
'''
text2 = '''
this is not my
multiline paragraph
'''
sys.stdout.write(text) # print text
sys.stdout.flush()
time.sleep(3) # sleep 3 seconds
go_to_start(text) # go to start
sys.stdout.write(text2) # overwrite text
Now, a problem that is very rarely talked about, as far as I've noticed, arises. If text2
were to be
text2 = '''
this is
multiline
'''
the original text would be left unchanged. This is because when you move to the start and overwrite text, only the text that is needed to be overwritten is overwritten. In this case, only 'this is'
and 'multiline'
would be overwritten, leaving ' my'
and ' text'
untouched. To fix this, you could write a new clear_to_start
function, that clears text as the cursor ascends to the top:
def clear_to_start(text):
lines = text.split('\n') # separate lines
lines = lines[::-1] # reverse list
nlines = len(lines) # number of lines
for i, line in enumerate(lines): # iterate through lines from last to first
sys.stdout.write('\r') # move to beginning of line
sys.stdout.write(' ' * len(line)) # replace text with spaces (thus overwriting it)
if i < nlines - 1: # not first line of text
sys.stdout.write('\x1b[1A') # move up one line
sys.stdout.write('\r') # move to beginning of line again
This function could then be used like so:
import sys
import time
def clear_to_start(text):
lines = text.split('\n') # separate lines
lines = lines[::-1] # reverse list
nlines = len(lines) # number of lines
for i, line in enumerate(lines): # iterate through lines from last to first
sys.stdout.write('\r') # move to beginning of line
sys.stdout.write(' ' * len(line)) # replace text with spaces (thus overwriting it)
if i < nlines - 1: # not first line of text
sys.stdout.write('\x1b[1A') # move up one line
sys.stdout.write('\r') # move to beginning of line again
text = '''
this is my
multiline text
'''
text2 = '''
this is
multiline
'''
sys.stdout.write(text) # print text
sys.stdout.flush()
time.sleep(3) # sleep 3 seconds
clear_to_start(text) # clear lines and ascend to top
sys.stdout.write(text2) # overwrite text