Created
September 17, 2019 18:23
-
-
Save TimothyLoyer/bc3c2fa25aab946488fee7878fc95e42 to your computer and use it in GitHub Desktop.
Python CLI Progress Bar
This file contains hidden or 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_items=None, title="Progress", bar_length=60): | |
self.title = title | |
self.bar_length = bar_length | |
self.total_items = total_items | |
self.start_time = timer() | |
self.is_tty = isatty(sys.stdin.fileno()) | |
def get_time_elapsed(self): | |
elapsed = timer() - self.start_time | |
return "{:d}:{:02d}m".format(int(elapsed // 60), int(elapsed % 60)) | |
def update_progress(self, progress): | |
# Only show the progress bar when using tty | |
if not self.is_tty: | |
return | |
status_message = "" | |
fraction = ( | |
"{:,}/{:,}".format(int(progress * self.total_items), self.total_items) | |
if self.total_items | |
else "" | |
) | |
if isinstance(progress, int): | |
progress = float(progress) | |
if not isinstance(progress, float): | |
progress = 0 | |
status_message = "- Error: progress var must be float\r\n" | |
if progress < 0: | |
progress = 0 | |
status_message = "- Halt...\r\n" | |
if progress >= 1: | |
progress = 1 | |
status_message = "- Done...\r\n" | |
block = int(round(self.bar_length * progress)) | |
text = "\r{}: [{}] {:0.1f}% {} {} {}".format( | |
self.title, | |
"#" * block + "-" * (self.bar_length - block), | |
progress * 100, | |
fraction, | |
self.get_time_elapsed(), | |
status_message, | |
) | |
sys.stdout.write(text) | |
sys.stdout.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment