| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Draws an animated terminal progress bar |
| 5 |
Usage: |
| 6 |
p = ProgressBar("blue") |
| 7 |
p.render(percentage, message) |
| 8 |
""" |
| 9 |
|
| 10 |
from rpython.tool import terminal |
| 11 |
import sys |
| 12 |
|
| 13 |
class ProgressBar(object): |
| 14 |
"""Terminal progress bar class""" |
| 15 |
TEMPLATE = ( |
| 16 |
'%(percent)-2s%% %(color)s%(progress)s%(normal)s%(empty)s %(message)s\n' |
| 17 |
) |
| 18 |
PADDING = 7 |
| 19 |
|
| 20 |
def __init__(self, color=None, width=None, block='.', empty=' '): |
| 21 |
""" |
| 22 |
color -- color name (BLUE GREEN CYAN RED MAGENTA YELLOW WHITE BLACK) |
| 23 |
width -- bar width (optinal) |
| 24 |
block -- progress display character (default '.') |
| 25 |
empty -- bar display character (default ' ') |
| 26 |
""" |
| 27 |
if color: |
| 28 |
self.color = getattr(terminal, color.upper()) |
| 29 |
else: |
| 30 |
self.color = '' |
| 31 |
if width and width < terminal.COLUMNS - self.PADDING: |
| 32 |
self.width = width |
| 33 |
else: |
| 34 |
|
| 35 |
self.width = terminal.COLUMNS - self.PADDING |
| 36 |
self.block = block |
| 37 |
self.empty = empty |
| 38 |
self.progress = None |
| 39 |
self.lines = 0 |
| 40 |
|
| 41 |
def render(self, percent, message = ''): |
| 42 |
"""Print the progress bar |
| 43 |
percent -- the progress percentage % |
| 44 |
message -- message string (optional) |
| 45 |
""" |
| 46 |
inline_msg_len = 0 |
| 47 |
if message: |
| 48 |
|
| 49 |
inline_msg_len = len(message.splitlines()[0]) |
| 50 |
if inline_msg_len + self.width + self.PADDING > terminal.COLUMNS: |
| 51 |
|
| 52 |
|
| 53 |
bar_width = terminal.COLUMNS - inline_msg_len -self.PADDING |
| 54 |
else: |
| 55 |
bar_width = self.width |
| 56 |
|
| 57 |
|
| 58 |
if self.progress != None: |
| 59 |
self.clear() |
| 60 |
self.progress = (bar_width * percent) / 100 |
| 61 |
data = self.TEMPLATE % { |
| 62 |
'percent': percent, |
| 63 |
'color': self.color, |
| 64 |
'progress': self.block * self.progress, |
| 65 |
'normal': terminal.NORMAL, |
| 66 |
'empty': self.empty * (bar_width - self.progress), |
| 67 |
'message': message |
| 68 |
} |
| 69 |
sys.stdout.write(data) |
| 70 |
sys.stdout.flush() |
| 71 |
|
| 72 |
self.lines = len(data.splitlines()) |
| 73 |
|
| 74 |
def clear(self): |
| 75 |
"""Clear all printed lines""" |
| 76 |
sys.stdout.write( |
| 77 |
self.lines * (terminal.UP + terminal.BOL + terminal.CLEAR_EOL) |
| 78 |
) |