Created
August 27, 2020 07:03
-
-
Save apoorvnandan/902e60649d3e8ebe265af7d2c0de251e to your computer and use it in GitHub Desktop.
Extremely simple progress bar in python
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
class ProgressBar: | |
def __init__(self, total, desc='', width=10): | |
self.total = total | |
self.width = width | |
self.header = f"{desc}: " if len(desc) > 0 else '' | |
self.i = 0 | |
self.__print_progress() | |
def __print_progress(self): | |
p = round((self.i*self.width) / self.total) | |
if self.i == self.total: | |
print(f"\r{self.header}[{'='*(self.width)}] {self.i}/{self.total}") | |
else: | |
print(f"\r{self.header}[{'='*(p) + ' '*(self.width-p)}] {self.i}/{self.total}", end='') | |
def update(self, step=1): | |
self.i += step | |
self.__print_progress() | |
def print(self, txt): | |
print(f"\r{' '*(self.width + len(self.header) + 20)}", end='\r') | |
print(f"{txt}") | |
self.__print_progress() | |
""" | |
## Usage | |
""" | |
import time | |
pbar = ProgressBar(123) | |
for i in range(123): | |
if i%50 == 0: | |
pbar.print(f"i = {i}") | |
pbar.update() | |
time.sleep(0.1) | |
pbar = ProgressBar(12, desc='training', width=40) | |
for i in range(12): | |
pbar.update() | |
time.sleep(0.1) | |
""" | |
Output: | |
``` | |
i = 0 | |
i = 50 | |
i = 100 | |
[==========] 123/123 | |
training: [========================================] 12/12 | |
``` | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment