4

Normally print ("{}".foo, end="\r") works well.

But the exception is when foo is long, and next time foo becomes short. The output becomes incorrect. Below is an example:

import time
print ("{}".format(1111), end="\r")
time.sleep(2)
print ("{}".format(2), end="\r")

First Output:

1111

Final Output (after 2 sec) - which is wrong:

2111

Expected Output

2

Attempts

Tried using flush=True with print, and sys.stdout.flush() but without luck.

Tested in Jupyter Notebook and iPython. Any idea how to optimize this in a simple way?

lesca
  • 429
  • 2
  • 11

2 Answers2

4

Try this if it works

import time
print ("{:<5}".format(1111), end="\r")
time.sleep(2)
print ("{:<5}".format(2), end="\r")
  • You could replace the 5 by `shutil.get_terminal_size().columns`, according to https://stackoverflow.com/questions/566746/how-to-get-linux-console-window-width-in-python it should be cross-platform. – Demi-Lune Apr 15 '20 at 09:11
  • This is the best answer until now. Marked it as answer. – lesca Apr 17 '20 at 03:55
3

You could use a class instance to remember what was printed last and overwrite it with spaces:

import time

class OverwriteLast:
    def __init__(self):
        self.last = 0
    def print(self,s):
        if self.last:
            print(' '*self.last, end='\r')
        self.last = len(s)
        print(s, end='\r')

over = OverwriteLast()

over.print("{}".format(1111))
time.sleep(2)
over.print ("{}".format(2))

Output as requested

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Right way to go and it works. I will wait for 1 more day to see if there will be simpler answer. Many thanks for this solution. – lesca Apr 15 '20 at 08:11