一个更清洁,更“即插即用”的版本@ Nagasaki45的回答:
def print_statusline(msg: str):
last_msg_length = len(print_statusline.last_msg) if hasattr(print_statusline, 'last_msg') else 0
print(' ' * last_msg_length, end='\r')
print(msg, end='\r')
sys.stdout.flush() # Some say they needed this, I didn't.
print_statusline.last_msg = msg
# Then simply use like this:
for msg in ["Initializing...", "Initialization successful!"]:
print_statusline(msg)
time.sleep(1)
# If you want to check that the line gets cleared properly:
for i in range(9, 0, -1):
print_statusline("{}".format(i) * i)
time.sleep(0.5)与其他许多答案不同,它可以使用不同长度的字符串正常工作,因为它会清空带有空格的行。也适用于Windows。