penfold1992
penfold1992

Reputation: 314

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?

Upvotes: 6

Views: 4980

Answers (4)

wellplayed
wellplayed

Reputation: 1048

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

Upvotes: 6

Louise Davies
Louise Davies

Reputation: 15951

I always find that Alexander Kukushkin's Jupyter Widget is the best for these sorts of things. It creates a nice looking progress bar, can work on generators and you can set how often it updates the progress value.

To use it, copy the code from the github link into a cell, then run your code like so:

large_number = 1000
for i in log_progress(range(large_number)):
    //your code here - no need to print anything manually!

Upvotes: 0

Engineero
Engineero

Reputation: 12928

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.

Upvotes: 2

Prasad
Prasad

Reputation: 6034

import sys

large_number = 1000
for i in range(large_number):
    print('{} / {} complete.'.format(i,large_number), end='\r')
    sys.stdout.flush()

Upvotes: 2

Related Questions