Search code examples
pythonpython-2.7progress-barnormalize

Python 2.7 - Progress Bar without External Library


I have a python function which extracts images from some sensor data file. The function loops over the images and extract them sequentialy.

There are around 25000 images within sensor data file. The number is not fixed. However I have a variable which dynamically stores the number of messages/images.

I want to design a progress bar by not using any external library. The progress bar print percentage completed with a '#' character similar to:

Progress 53%: #########################

How I can normalize the number of images between 1-100%?


Solution

  • There isn't really a great way of doing the percentage while having it work inside of IDLE (because idle doesn't support any clearing or \b).

    So, instead, I simply made it a visual progress bar:

    from __future__ import print_function
    import time
    
    class Progress():
        def __init__(self, total_images):
            self.total_images = total_images
            self.bar_width = 5
            self.previous = 0
            self.prompt = "Progress: "
            print(self.prompt, end='')
    
        def update(self, image_number):
            percentage = float(image_number) / self.total_images
            number_of_ticks = percentage * self.bar_width
            delta = int(number_of_ticks - self.previous)
            self.previous = int(number_of_ticks)
            if delta > 0:
                print("#" * delta, end='')
    
    total_images = 10
    progress_bar = Progress(total_images)
    for current_image in range(1, total_images+1):
        progress_bar.update(current_image)
        time.sleep(.1)
    

    Output:

    Progress: #####
    

    If you want a longer bar, you can modify the self.bar_width property. Optionally, you could add all of these as argument, but I was unsure as to which ones you'd find useful.