diff --git a/progress_logger.py b/progress_logger.py new file mode 100644 index 0000000000..365636c6ca --- /dev/null +++ b/progress_logger.py @@ -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 \ No newline at end of file