Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions progress_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import sys

class ProgressLogger:
"""A utility class to log output dynamically with a progress bar."""

def __init__(self, total_steps: int, width: int = 50, fill: str = "=", empty: str = " ", prefix: str = "[", suffix: str = "]") -> None:
"""
Initialize the ProgressLogger instance.

:param total_steps: The total number of steps to track.
:param width: The width of the progress bar. Default is 50.
:param fill: The character to use for the filled part of the progress bar. Default is "=".
:param empty: The character to use for the empty part of the progress bar. Default is " ".
:param prefix: The character to use as the prefix of the progress bar. Default is "[".
:param suffix: The character to use as the suffix of the progress bar. Default is "]".
"""
self.total_steps = total_steps
self.width = width
self.fill = fill
self.empty = empty
self.prefix = prefix
self.suffix = suffix
self.current_step = 0
self.print_progress_bar()

def update(self, step: int) -> None:
"""
Update the progress bar and print the new status.

:param step: The current step number.
"""
self.current_step = step
self.print_progress_bar()

def print_progress_bar(self) -> None:
"""Print the progress bar with the current progress."""
percentage = (self.current_step / self.total_steps) * 100
filled_length = int(self.width * (percentage / 100))
empty_length = self.width - filled_length

progress_bar = self.prefix + self.fill * filled_length + self.empty * empty_length + self.suffix
sys.stdout.write("\r{:3.0f}% {}".format(percentage, progress_bar))
sys.stdout.flush()

if self.current_step == self.total_steps:
print() # Move to a new line when finished