Created
December 7, 2020 08:31
-
-
Save M0r13n/a229e234c1a27b43cf6cf68d35999250 to your computer and use it in GitHub Desktop.
A simple Progress Bar in Python without external dependencies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Dynamic Progressbar in Python without external dependencies | |
""" | |
import sys | |
import time | |
from typing import TextIO, Iterable | |
class ProgressBar(object): | |
def __init__(self, total: int, count: int = 0, status: str = "", out_file: TextIO = sys.stdout, bar_len: int = 60): | |
self.count: int = count | |
self.total: int = total | |
self.status: str = status | |
self.out_file: TextIO = out_file | |
self.bar_len: int = bar_len | |
def __enter__(self) -> "ProgressBar": | |
return self | |
def __exit__(self, *exc): | |
self.out_file.flush() | |
def set_count(self, c: int): | |
self.count = c | |
def set_status(self, status: str): | |
self.status = status | |
def update_count(self, c: int): | |
self.set_count(c) | |
self.write() | |
def update_status(self, s: str): | |
self.status = s | |
self.write() | |
def update(self, count: int, status: str): | |
self.set_count(count) | |
self.set_status(status) | |
self.write() | |
def write(self): | |
filled_len = int(round(self.bar_len * self.count / float(self.total))) | |
percents = round(100.0 * self.count / float(self.total), 1) | |
bar = '=' * filled_len + '-' * (self.bar_len - filled_len) | |
sys.stdout.write(f'[{bar}] {percents}%...{self.status}\r') | |
sys.stdout.flush() | |
class ProgressRange(object): | |
def __init__(self, stop: int, start: int = 0, step: int = 1): | |
self._stop: int = stop | |
self._start: int = start | |
self._step: int = step | |
self._range = iter(range(start, stop, step)) | |
self._bar: "ProgressBar" = ProgressBar(count=start, total=stop) | |
self._cur: int = start | |
def __iter__(self): | |
return self | |
def __next__(self): | |
r = next(self._range) | |
self._cur += self._step | |
self._bar.update(self._cur, f"{self._cur} / {self._stop}") | |
return r | |
if __name__ == '__main__': | |
for i in ProgressRange(10): | |
time.sleep(1.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment