0

I have a code like this:

import time

print("some previous print", end='\r', flush=True)

for i in range(10):
    print("progress " + str(i), end='\r', flush=True)
    time.sleep(1)

The result is something like progress 9ous print - so it just cuts previous print by length.

I could have something like end=' \r' to make length longer, but not ideal and flexible solution. Any ideas?

Michal Palko
  • 601
  • 1
  • 4
  • 14
  • 1
    Does this answer your question? [\r in Python does not delete the entire line](https://stackoverflow.com/questions/63660820/r-in-python-does-not-delete-the-entire-line) – Pranav Hosangadi Feb 11 '22 at 21:14
  • What is your expected/wanted output? – hc_dev Feb 11 '22 at 21:14
  • @Pranav Hosangadi Exactly! Thank you. I wonder I have not found it myself (I was searching for a while). – Michal Palko Feb 11 '22 at 21:20
  • See also [`progressbar2` and deleting line in console](https://stackoverflow.com/questions/63954472/delete-last-line-in-console-to-write-shorter-message-python) – hc_dev Feb 11 '22 at 21:23

1 Answers1

0

To solve:

  • prepend an additional carriage-return (CR or \r) before the output-string
  • and make sure all previous printed characters are over-written (if necessary by space):
import time

print("About to start shortly.", end='\r', flush=True)
time.sleep(3)
print(" "*50, end='\r', flush=True) # overwritting a length of 50 with space

for i in range(10):
    print(f"\rprogress {i:2}", end='\r', flush=True)  # prefixed with CR, f-string right-aligned
    time.sleep(1)

Note: the status-lines have a constant width of 11 (9+ 2 digits reserved for the number, right-aligned).

hc_dev
  • 8,389
  • 1
  • 26
  • 38