0

I'm trying to print a progress bar using end=\r with print(), but the Jupyter notebook output still has new lines.

for i in range(0, 100000):
    print(i, end='\r')

Output:

2478
4867
6957
8970
11405
...

I'm running the server on Ubuntu 18.04 and am accessing it using Chrome on a Mac. How can I make the carriage return work?

Kingsley
  • 14,398
  • 5
  • 31
  • 53
Justin Zhang
  • 45
  • 1
  • 7

1 Answers1

2

There is nothing wrong with your code. Running in plain Ubuntu 18 / Python3 it behaves as expected.

I guess this is some kind of buffering issue (or a bug in Jupyter).

Based on the link @unutbu posted, it seems that only a minor time delay is needed to allow Jupyter to get its ship in shape.

import time
for i in range(100000):
    print(i, end='\r')
    time.sleep(0)  # EDIT, somehow even this works too.
print("")  

Obviously if you really do have a huge amount of output (like 100k lines), this is far from ideal. But the real delay is in the flushing and re-painting of the screen, not the actual time.sleep().

If you are doing this sort of thing in a quick-repetition loop, it may be better to only update the progress-bar once every few seconds (or so). This can be accomplished by checking for a time delta.

Kingsley
  • 14,398
  • 5
  • 31
  • 53