It's pretty easy to roll your own if you're only working with a single line. Chr(8)
(backspace) moves the cursor back a space. Keep track of how many characters you have printed on a line, don't print a newline at the end, and print enough backspaces to get back to where you want to be to print the new text. If the new text is shorter that what's already there, print enough spaces to erase the extra. The only real trick is to make sure you flush output, otherwise it won't show up until you print a newline. (As of Python 3.3 there's a flush
parameter on the print()
function, which makes that easy.)
Here's a little demo... I was aiming to make Line
something resembling an API for this, but don't really have the time to do it properly. Still, maybe you can take it from here...
import time
from io import StringIO
class Line():
def __init__(self):
self.value = ""
def __call__(self, *args, start=0, sep=" "):
chars = 0
io = StringIO()
print(*args, file=io, end="", sep=sep)
text = io.getvalue()
self.value = (self.value[:start] + " " * (start - len(self.value))
+ text + self.value[start + len(text):])
print(self.value, chr(8) * len(self.value), sep="", end="", flush=True)
def __next__(self):
self.value = ""
print()
def greet():
line = Line()
line("hello", start=2)
time.sleep(1)
line("world", start=8)
time.sleep(1)
line("hi ", start=2)
time.sleep(1)
line("world ", start=7)
time.sleep(0.3)
line("world ", start=6)
time.sleep(0.3)
line("world ", start=5)
time.sleep(1)
line("globe", start=5)
time.sleep(1)
for _ in range(4):
for c in "! ":
line(c, start=10)
time.sleep(0.3)
line("!", start=10)
time.sleep(1)
next(line)
greet()