#!/usr/bin/env python# -*- coding: utf-8 -*-"""
Progress Bar
~~~~~~~~~~~~
Display a progress bar on the console.
:Copyright: 2001-2007 Jochen Kupperschmidt
:License: MIT
"""fromitertoolsimportcycleimportsysfromtimeimportsleepclassProgressBar(object):"""Visualize a status bar on the console."""def__init__(self,max_width):"""Prepare the visualization."""self.max_width=max_widthself.spin=cycle(r'-\|/').nextself.tpl='%-'+str(max_width)+'s ] %c%5.1f%%'show(' [ ')self.last_output_length=0defupdate(self,percent):"""Update the visualization."""# Remove last state.show('\b'*self.last_output_length)# Generate new state.width=int(percent/100.0*self.max_width)output=self.tpl%('-'*width,self.spin(),percent)# Show the new state and store its length.show(output)self.last_output_length=len(output)defshow(string):"""Show a string instantly on STDOUT."""sys.stdout.write(string)sys.stdout.flush()defpercentize(steps):"""Generate percental values."""foriinrange(steps+1):yieldi*100.0/stepsif__name__=='__main__':# An example progress bar with 40 segments,# filled in 20 steps, updated every 0.1 seconds.sb=ProgressBar(40)forpercentinpercentize(20):sb.update(percent)sleep(0.1)show('\n')