How to display a progress bar in Jupyter Notebook

How to display a progress bar in Jupyter Notebook

Usually, when we run long computations we include some print statements like this one:

1
2
3
4
5
6
7
8
number_of_elements = 1000

for i in range(number_of_elements):
    if i % 100 == 0:
        print(i)
    time.sleep(0.01) #Here should be the code that does the computation.

print('Done')

We end up with something similar to this output:

We do it because we wonder whether the Notebook is still running. We want to see the progress. That is sufficient, but it does not look good, does it?

What if we could display a progress bar? We can! Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import time, sys
from IPython.display import clear_output

def update_progress(progress):
    bar_length = 20
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
    if progress < 0:
        progress = 0
    if progress >= 1:
        progress = 1

block = int(round(bar_length * progress))

clear_output(wait = True)
    text = "Progress: [{0}] {1:.1f}%".format( "#" * block + "-" * (bar_length - block), progress * 100)
    print(text)

And now, when we run the computation we see a nice progress bar ;)

1
2
3
4
5
6
7
number_of_elements = 1000

for i in range(number_of_elements):
    time.sleep(0.1) #Replace this with a real computation
    update_progress(i / number_of_elements)

update_progress(1)

The solution is based on Philip Osborne’s blog post and an answer to the StackOverflow question.


Remember to share on social media!
If you like this text, please share it on Facebook/Twitter/LinkedIn/Reddit or other social media.

If you watch programming live streams, check out my YouTube channel.
You can also follow me on Twitter: @mikulskibartosz

For business inquiries, send me a message on LinkedIn or Twitter.


Bartosz Mikulski
Bartosz Mikulski * data scientist / software engineer * conference speaker * organizer of School of A.I. meetups in Poznań * co-founder of Software Craftsmanship Poznan & Poznan Scala User Group