由pyskydrive工程(http://code.google.com/p/pyskydrive/)中發現的進度條,加了一點修改!
import os<br />import sys<br />import cmd<br />import unicodedata<br />from threading import Thread<br />from time import sleep</p><p>class ProgressBar(Thread):<br /> """A simple text progress bar control."""</p><p> def __init__(self):<br /> self.running = True<br /> self.percent = -1<br /> self.msg = ""<br /> Thread.__init__(self)</p><p> def run(self):<br /> i = 1<br /> while self.running and self.percent < 100:<br /> display = '/r'</p><p> if self.msg != "":<br /> display += self.msg + ' '</p><p> if self.percent >= 0:<br /> display += str(self.percent) + '% '<br /> display += '-' * (40 * self.percent / 100)</p><p> if i + 1 + len(display) > 80:<br /> i = 1</p><p> display += '-' * i<br /> display += '>'<br /> display += ' ' * (80 - len(display))<br /> sys.stderr.write(display)</p><p> i += 1<br /> sleep(0.5)</p><p> sys.stderr.write('/r' + ' ' * 79 + '/r')<br /> sys.stderr.flush()</p><p> def stop(self):<br /> """Stop displaying progress bar.</p><p> Note: there may be latency to stop. You'd better wait for the thread<br /> stops. See _stop_progress(t_bar).</p><p> """<br /> self.running = False</p><p> def set_percent(self, percent, msg = ""):<br /> """Call back method for owner of progress bar."""<br /> self.percent = int(percent)<br /> self.msg = msg</p><p> def is_alive(self):<br /> return self.isAlive()</p><p>def _start_progress():<br /> """Display a progress bar"""<br /> t_bar = ProgressBar()<br /> t_bar.start()<br /> return t_bar </p><p>def _stop_progress(t_bar):<br /> """Hide the progress bar"""<br /> if hasattr(t_bar, "is_alive"):<br /> alive = t_bar.is_alive()<br /> else:<br /> alive = t_bar.isAlive()</p><p> if t_bar and alive:<br /> t_bar.stop()<br /> t_bar.join()</p><p>def _set_progress(t_bar,percent,msg = ""):<br />t_bar.set_percent(percent)</p><p>def _print_msg(t_bar, *args):<br /> """Hide the progress bar and print message"""</p><p> assert t_bar is None or isinstance(t_bar, ProgressBar)</p><p> if t_bar and t_bar.is_alive():<br /> _stop_progress(t_bar)</p><p> print ' '.join(args)</p><p>def _unicode_str_width(text):<br /> """Calculate the exact width of unicode string."""</p><p> width = 0<br /> for char in text:<br /> if isinstance(char, unicode):<br /> if unicodedata.east_asian_width(char) in ('F', 'W', 'A'):<br /> width += 2<br /> else:<br /> width += 1<br /> else:<br /> width += 1</p><p> return width</p><p>#Test the progress bar<br />if __name__ == "__main__":<br />t_bar = _start_progress()<br />count = 0;<br />while count<100:<br />_set_progress(t_bar,count,'%d'%(count))<br />sleep(0.1)<br />count = count+1</p><p>_stop_progress(t_bar)<br />print "Done!"
*其實幾個控制函數還可以封裝到一個類中使用,那就更為方便了!