mptrossbach
mptrossbach

Reputation: 384

print() with flush=True is not fully clearing print output when subsequent output is a shorter length

If you run this code for a few iterations you will see that a print message followed by a shorter print message will result in some part of the longer message being left in the output of the shorter message.

import random
import time

names = ['Mike', 'Alexander', 'Tom', 'Johnny']
numbers = list(range(0, 10))
while True:
    name = random.choice(names)
    number = random.choice(numbers)
    print('\rName: {} - Number: {}'.format(name, number), end='', flush=True)
    time.sleep(1)

EDIT

I changed the code to this which resolved the problem:

import random
import time

names = ['Mike', 'Alexander', 'Tom', 'Johnny']
numbers = list(range(0, 10))
msg_len = 0
while True:
    name = random.choice(names)
    number = random.choice(numbers)
    msg = '\rName: {} - Number: {}'.format(name, number)
    buffer = msg_len - len(msg)
    buffer = buffer if buffer > 0 else 0
    print(msg, end=' '*buffer, flush=True)
    msg_len = len(msg)
    time.sleep(1)

Upvotes: 0

Views: 153

Answers (1)

Prune
Prune

Reputation: 77827

It hasn't been left in the output, per se. You're reprinting on the same line, but this does not include an implicit cleaning of the previous output. If you want to erase that, you need to do so actively, such as overwriting the previous line length with blanks.

Upvotes: 1

Related Questions