Source code

Revision control

Other Tools

1
# This Source Code Form is subject to the terms of the Mozilla Public
2
# License, v. 2.0. If a copy of the MPL was not distributed with this
3
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5
# Text progress bar library, like curl or scp.
6
7
import sys
8
import datetime
9
import time
10
11
12
class ProgressBar(object):
13
def __init__(self, label, limit, label_width=12):
14
self.label = label
15
self.limit = limit
16
self.label_width = label_width
17
self.cur = 0
18
self.t0 = datetime.datetime.now()
19
self.fullwidth = None
20
21
self.barlen = 64 - self.label_width
22
self.fmt = '\r%-' + str(label_width) + 's %3d%% %-' + str(self.barlen) + 's| %6.1fs'
23
24
def update(self, value):
25
self.cur = value
26
pct = int(100.0 * self.cur / self.limit)
27
barlen = int(1.0 * self.barlen * self.cur / self.limit) - 1
28
bar = '='*barlen + '>'
29
dt = datetime.datetime.now() - self.t0
30
dt = dt.seconds + dt.microseconds * 1e-6
31
line = self.fmt % (self.label[:self.label_width], pct, bar, dt)
32
self.fullwidth = len(line)
33
sys.stdout.write(line)
34
sys.stdout.flush()
35
36
# Clear the current bar and leave the cursor at the start of the line.
37
def clear(self):
38
if (self.fullwidth):
39
sys.stdout.write('\r' + ' ' * self.fullwidth + '\r')
40
self.fullwidth = None
41
42
def finish(self):
43
self.update(self.limit)
44
sys.stdout.write('\n')
45
46
47
if __name__ == '__main__':
48
pb = ProgressBar('test', 12)
49
for i in range(12):
50
pb.update(i)
51
time.sleep(0.5)
52
pb.finish()