Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jupyter Notebook Counter when processing

I am using Jupyter Notebook and Python 3.0.

I have a block of code that takes a while to execute in Jupyter Notebook and to identify its current status, I would like to make a counter of what loop it is on, something like this:

large_number = 1000
for i in range(large_number):
    print('{} / {} complete.'.format(i,large_number))

The problem with this is that it will print a new line for each iteration, which I do not want to do... instead I just want to update the value.

Is there anyway I can do this in Jupyter Notebook?

like image 239
penfold1992 Avatar asked Nov 07 '17 18:11

penfold1992


3 Answers

The de facto standard for this functionality in Jupyter is tqdm, specifically tqdm_notebook. It is simple to use, provides informative output, and has a multitude of options. You can also use it for cli work.

from tqdm import tqdm_notebook
from time import sleep

for i in tqdm_notebook(range(100)):
    sleep(.05)

The output would be something like this:

enter image description here

like image 192
wellplayed Avatar answered Nov 06 '22 07:11

wellplayed


I'm fond of making an ascii status bar. Say you need to run 1000 iterations and want to see 20 updates before it is done:

num_iter = 1000
num_updates = 20
update_per = num_iter // num_updates  # make sure it's an integer
print('|{}|'.format(' ' * (num_updates - 2)))  # gives you a reference
for i in range(num_iter):
    # code stuff
    if i % update_per == 0:
        print('*', end='', flush=True)

Gives you an update that looks like:

|                  |
*******

as it runs.

like image 27
Engineero Avatar answered Nov 06 '22 07:11

Engineero


import sys

large_number = 1000
for i in range(large_number):
    print('{} / {} complete.'.format(i,large_number), end='\r')
    sys.stdout.flush()
like image 2
Prasad Avatar answered Nov 06 '22 08:11

Prasad