A Simple Progress Bar in Python

I needed a way to display the progress of data processing program written in Python on console. I wanted to include a progress bar to show the progress. While Python packages like tqdm serve this purpose well, restrictions behind a firewall prevented me from installing and using them. As a solution, I wrote this simple progress bar from the ground up:


import sys
import time

def simple_progressbar(iterable, desc="Processing", bar_length=20):
    total_items = len(iterable)

    def print_progress_bar(completed):
        percent_complete = completed / total_items * 100
        bar = ('#' * int(bar_length * percent_complete / 100)).ljust(bar_length)
        sys.stdout.write(f"\r{desc}: [{bar}] {percent_complete:.2f}%")
        sys.stdout.flush()

    for index, item in enumerate(iterable):
        yield item
        print_progress_bar(index + 1)
    
    sys.stdout.write("\n")
    sys.stdout.flush()

# Example usage
items = [...]  # Replace with your iterable

for item in simple_progressbar(items):
    # Your actual processing logic
    time.sleep(0.1)