Change color of manual tqdm progress bar when finished in Jupyter notebook

Question:

I want to use a manual progress bar from tqdm in a Jupyter notebook with a nested loop. To have an overview over all iterations, I use a manual update of the progress bar as follows:

from tqdm.notebook import tqdm

a = range(100)
b = range(5)
pbar = tqdm(total=len(a)*len(b))

for a_ in a:
  for b_ in b:
    pbar.update(1)
    pbar.refresh()

progress bar

However, when the total number of iterations is reached (i.e., 100%), the color is still blue. But if I use something like for i in trange(100): ... , the progress bar turns green after finishing.

Can someone tell me how to achieve the same behavior for the manual progress bar? Thanks for help!

Asked By: akra1

||

Answers:

Found this code on stackoverflow:

def progress_function(chunk, file_handling, bytes_remaining):
 '''
 function to show the progress of the download
 '''
 global filesize
 filesize=chunk.filesize
 current = ((filesize - bytes_remaining)/filesize)
 percent = ('{0:.1f}').format(current*100)
 progress = int(50*current)
 status = '█' * progress + '-' * (50 - progress)

You can edit this code to this:

def progress_function(chunk, file_handling, bytes_remaining):
  '''
  function to show the progress of the download
  '''
  global filesize
  filesize=chunk.filesize
  current = ((filesize - bytes_remaining)/filesize)
  percent = ('{0:.1f}').format(current*100)
  progress = int(50*current)
  status = '█' * progress + '-' * (50 - progress)
  #change the color of the progress bar to green when the download is complete
  if bytes_remaining == 0:
      status = '33[92m' + status + '33[0m'
  sys.stdout.write(' ↳ |{bar}| {percent}%r'.format(bar=status, 
      percent=percent))
  sys.stdout.flush()

This will turn the progress bar to green when it is done.
I don’t know whether it will help you or not. But, check it out anyway 🙂

Answered By: Just someone

I think pbar.close() can do it.

from tqdm.notebook import tqdm

a = range(100)
b = range(5)
pbar = tqdm(total=len(a)*len(b))

for a_ in a:
  for b_ in b:
    pbar.update(1)
    pbar.refresh()
pbar.close()
Answered By: Oivalf
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.