Created
November 17, 2017 11:32
-
-
Save kgori/50c2ab17a11ac18de9436ea3d515d9ea to your computer and use it in GitHub Desktop.
Simple 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
import sys | |
class Progress(): | |
def __init__(self, capacity, label = '', width=80, fill='#', blank=' '): | |
self.capacity = capacity | |
self.label = label | |
self.width = width | |
self.fill = fill | |
self.blank = blank | |
self.completed = 0 | |
def __str__(self): | |
pc = self._percent() | |
s = '\r\033[K{0}[{1}{2}] {3:.2f}%{4}'.format( | |
self.label, | |
self.fill*self._fillchars(), | |
self.blank*self._blankchars(), | |
pc * 100, | |
'\n' if pc >= 1 else '' | |
) | |
return s | |
def update(self, n): | |
if self.completed >= self.capacity: | |
return | |
self.completed += n | |
sys.stdout.write(self.__str__()) | |
sys.stdout.flush() | |
def _percent(self): | |
return float(self.completed) / self.capacity | |
def _fillchars(self): | |
pc = self._percent() | |
return int(pc * (self.width - 2)) | |
def _blankchars(self): | |
return self.width - 2 - self._fillchars() | |
if __name__ == '__main__': | |
import time | |
# Demo | |
p = Progress(250, 'xoxo') | |
for i in range(250): | |
p.update(1) | |
time.sleep(0.02) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment