Skip to content

Instantly share code, notes, and snippets.

@daryl314
Created October 6, 2017 13:22
Show Gist options
  • Select an option

  • Save daryl314/964ca738a339577af965d821ae5e7d1e to your computer and use it in GitHub Desktop.

Select an option

Save daryl314/964ca738a339577af965d821ae5e7d1e to your computer and use it in GitHub Desktop.
Python ANSI progress bar
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