Created
October 6, 2017 13:22
-
-
Save daryl314/964ca738a339577af965d821ae5e7d1e to your computer and use it in GitHub Desktop.
Python ANSI 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,subprocess,time | |
| class ProgressBar: | |
| """Class to handle a progress bar for a given job size""" | |
| def __init__(self, jobSize, leader='', logger=sys.stdout, maxCols=80): | |
| ttyr,ttyc = self.ttysize() | |
| self.nCols = min(ttyc,maxCols-2) - len(leader) | |
| self.n = jobSize | |
| self.counter = 0 | |
| self.logger = logger | |
| self.logger.write(leader + '[' + ' '*self.nCols + ']') | |
| self.moveLeft(self.nCols + 1) | |
| self.logger.flush() | |
| def moveLeft(self, n=1): | |
| """Move counter specified number of spaces to left""" | |
| self.logger.write('\033[%dD' % n) | |
| def update(self, n=1): | |
| """Increment counter""" | |
| newBars = self.position(self.counter+n) - self.position(self.counter) | |
| self.logger.write('-'*newBars) | |
| self.logger.flush() | |
| self.counter += n | |
| if self.counter == self.n: | |
| self.logger.write('\n') | |
| def position(self, counter): | |
| """Return the bar position for a specified counter value""" | |
| return self.nCols * counter / self.n | |
| @staticmethod | |
| def ttysize(): | |
| """Return the size of the terminal window""" | |
| return map(int, subprocess.check_output(['stty','size']).split()) | |
| if __name__ == '__main__': | |
| bar = ProgressBar(50, leader='Updating ') | |
| for i in range(50): | |
| bar.update() | |
| time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment