michael@0: # This Source Code Form is subject to the terms of the Mozilla Public michael@0: # License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: # file, You can obtain one at http://mozilla.org/MPL/2.0/. michael@0: michael@0: # Text progress bar library, like curl or scp. michael@0: michael@0: import sys, datetime michael@0: michael@0: class ProgressBar(object): michael@0: def __init__(self, label, limit, label_width=12): michael@0: self.label = label michael@0: self.limit = limit michael@0: self.label_width = label_width michael@0: self.cur = 0 michael@0: self.t0 = datetime.datetime.now() michael@0: self.fullwidth = None michael@0: michael@0: self.barlen = 64 - self.label_width michael@0: self.fmt = '\r%-' + str(label_width) + 's %3d%% %-' + str(self.barlen) + 's| %6.1fs' michael@0: michael@0: def update(self, value): michael@0: self.cur = value michael@0: pct = int(100.0 * self.cur / self.limit) michael@0: barlen = int(1.0 * self.barlen * self.cur / self.limit) - 1 michael@0: bar = '='*barlen + '>' michael@0: dt = datetime.datetime.now() - self.t0 michael@0: dt = dt.seconds + dt.microseconds * 1e-6 michael@0: line = self.fmt%(self.label[:self.label_width], pct, bar, dt) michael@0: self.fullwidth = len(line) michael@0: sys.stdout.write(line) michael@0: sys.stdout.flush() michael@0: michael@0: # Clear the current bar and leave the cursor at the start of the line. michael@0: def clear(self): michael@0: if (self.fullwidth): michael@0: sys.stdout.write('\r' + ' ' * self.fullwidth + '\r') michael@0: self.fullwidth = None michael@0: michael@0: def finish(self): michael@0: self.update(self.limit) michael@0: sys.stdout.write('\n') michael@0: michael@0: if __name__ == '__main__': michael@0: pb = ProgressBar('test', 12) michael@0: for i in range(12): michael@0: pb.update(i) michael@0: time.sleep(0.5) michael@0: pb.finish()