|
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, datetime |
|
8 |
|
9 class ProgressBar(object): |
|
10 def __init__(self, label, limit, label_width=12): |
|
11 self.label = label |
|
12 self.limit = limit |
|
13 self.label_width = label_width |
|
14 self.cur = 0 |
|
15 self.t0 = datetime.datetime.now() |
|
16 self.fullwidth = None |
|
17 |
|
18 self.barlen = 64 - self.label_width |
|
19 self.fmt = '\r%-' + str(label_width) + 's %3d%% %-' + str(self.barlen) + 's| %6.1fs' |
|
20 |
|
21 def update(self, value): |
|
22 self.cur = value |
|
23 pct = int(100.0 * self.cur / self.limit) |
|
24 barlen = int(1.0 * self.barlen * self.cur / self.limit) - 1 |
|
25 bar = '='*barlen + '>' |
|
26 dt = datetime.datetime.now() - self.t0 |
|
27 dt = dt.seconds + dt.microseconds * 1e-6 |
|
28 line = self.fmt%(self.label[:self.label_width], pct, bar, dt) |
|
29 self.fullwidth = len(line) |
|
30 sys.stdout.write(line) |
|
31 sys.stdout.flush() |
|
32 |
|
33 # Clear the current bar and leave the cursor at the start of the line. |
|
34 def clear(self): |
|
35 if (self.fullwidth): |
|
36 sys.stdout.write('\r' + ' ' * self.fullwidth + '\r') |
|
37 self.fullwidth = None |
|
38 |
|
39 def finish(self): |
|
40 self.update(self.limit) |
|
41 sys.stdout.write('\n') |
|
42 |
|
43 if __name__ == '__main__': |
|
44 pb = ProgressBar('test', 12) |
|
45 for i in range(12): |
|
46 pb.update(i) |
|
47 time.sleep(0.5) |
|
48 pb.finish() |