Skip to content

Instantly share code, notes, and snippets.

@felixbd
Last active June 22, 2024 14:00
Show Gist options
  • Save felixbd/7fec739f89fa122b7eb28e8ce90747b1 to your computer and use it in GitHub Desktop.
Save felixbd/7fec739f89fa122b7eb28e8ce90747b1 to your computer and use it in GitHub Desktop.
Simple progress bar in python3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple progress bar.
Copyright (c) 2024 - Felix Drees - WTFPL
Do What the Fuck You Want to Public License
"""
def progress_bar_str(x: float) -> str:
"""
Print a progress bar with a percentage.
:param x: float from 0 to 1
:return: str with the progress bar and the percentage
"""
if 0 > x or 1 < x:
raise ValueError("[PROGRESS BAR ERROR] param has to be in [0, 1] (float)")
return f"[{'#' * int(x * 100):*<100}] {x:.2%}"
def progress_bar_old(generator: iter) -> iter:
"""
Simple progress bar for generator
:param generator: the iter you want to iterate
:returns: the iterated elements (the generator itself), BUT ADDS SIDE EFFECTS :D
"""
total: int = len(generator)
current: int = 0
for e in generator:
yield e
current += 1
print(progress_bar_str(current / total), end='\r')
else:
print("", end="\n")
def progress_bar(gen: iter) -> iter:
total, current = len(gen), 0
for e in gen:
yield e
current += 1
print(f"[{'#' * (current * 100 // total):*<100}] {current / total:.2%}", end='\r')
print()
if __name__ == '__main__':
import time
for k in progress_bar(range(0, 110, 10)):
time.sleep(0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment