Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 3d2b0f8788
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 95 lines (84 sloc) 2.325 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
#!/usr/bin/env python
# progress.py

"""A class for drawing a progress bar to the console in various styles."""

import os
import time
import sys
import math

class ProgressBar:

def __init__(self, maxValue, style="percent"):
self.style = style
self.current = 0
self.maxValue = maxValue
# Get the width of the current console
_,self.width = os.popen('stty size', 'r').read().split()
# It is returned as a string. Fix that.
self.width = int(self.width)
self.firstDraw = True
if style=="percent":
# [****----] 50%
# Leave space for the sides (2), the brackets(2), the percent (3)
# and the space between the brackets and percent (1).
self.width -= 8
if style=="plain":
# [******------]
# Leave space for the sides (2) and the brackets (2).
self.width -= 4
if style=="numbers":
# [***---] 25/50
# The biggest number is xxx/xxx, so numOfDigits*2+1 for the numbers
# then 2 more for spaces on either side of the bar, 2 for the
# brackets.
numDigits = math.ceil(math.log10(maxValue))
self.width -= int(numDigits * 2 + 5)

"""Update the value of the progress bar, and by default redraw it."""
def update(self,value,redraw=True):
self.current = value
if redraw:
self.draw()

templates = {
'percent': ' [{0}{1}]{2:>3}% ',
'numbers': ' [{0}{1}]{3}/{4} ',
'plain' : ' [{0}{1}] '
}

"""Draw the progress bar to the screen in the specifed style."""
def draw(self):
percent = self.current / (self.maxValue * 1.0)
if percent > 1:
percent = 1
stars = int(self.width * percent)
blanks = self.width - stars

bar = ProgressBar.templates[self.style].format('*'*stars, ' '*blanks,
int(percent*100), self.current, self.maxValue)

# Reset the cursor to the beginning of the line
sys.stdout.write("\r")
# Write over the old progress bar
sys.stdout.write(bar)
# Refresh the console
sys.stdout.flush()

"""Some testing/demo code."""
if __name__ == "__main__":
bar = ProgressBar(50,style="plain")
n = 0
while n <= 50:
bar.update(n)
bar.draw()
n += 1
time.sleep(0.05)
print
bar = ProgressBar(50,style="percent")
n = 0
while n <= 50:
bar.update(n)
bar.draw()
n += 1
time.sleep(0.05)
print
bar = ProgressBar(50,style="numbers")
n = 0
while n <= 50:
bar.update(n)
bar.draw()
n += 1
time.sleep(0.05)
print
Something went wrong with that request. Please try again.