python-progressbarでターミナル上にプログレスバーを出そう
debianやubuntuにはパッケージもあります。使い方は簡単でした:
from progressbar import * widgets = ["Test: ", Percentage(), Bar()] maxval = 1000 pbar = ProgressBar(maxval=maxval, widgets=widgets).start() import time for i in range(maxval): time.sleep(0.001) pbar.update(pbar.currval + 1) pass pbar.finish()
widgetsとmaxvalを指定してProgressBarインスタンスをつくり、処理ごとにupdateメソッドを数値が増えるように呼び出し、最後にfinishメソッドを呼ぶだけです。
ターミナルでの表示はstderrに以下のようにでます
Test: 29%|################### |
標準であるwidgetはETA, FileTransferSpeed, RotatingMarker, Percentage, SimpleProgress と Bar, ReverseBarがあります。
ネタ: GoogleBar
カスタムwidget例として、Google Japan Blog: 20%ルールの話 のプログレス表示でGooogle...と表示させるっぽい GoogleBarを書いてみました。
from progressbar import * # imitate: http://googlejapan.blogspot.com/2007/07/20.html class GoogleBar(ProgressBarWidgetHFill): def __init__(self, colorful=True): self.colorful = colorful pass def update(self, pbar, width): # see: http://www.frexx.de/xterm-256-notes/ clear = "\033[0m" if self.colorful else "" red = "\033[31m" if self.colorful else "" green = "\033[32m" if self.colorful else "" yellow = "\033[33m" if self.colorful else "" blue = "\033[34m" if self.colorful else "" rate = float(pbar.percentage()) / 100 inside = width - 2 ps = int(rate * inside) sp = inside - ps bar = "|" if ps > 5: bar += "%s%s" % (blue, "G") if ps > 4: bar += "%s%s" % (red, "o") if ps > 3: bar += "%s%s" % (yellow, "o") if ps > 6: bar += "%s%s" % (yellow, "o" * (ps - 6)) if ps > 2: bar += "%s%s" % (blue, "g") if ps > 1: bar += "%s%s" % (green, "l") if ps > 0: bar += "%s%s" % (red, "e") bar += clear if sp > 0: bar += "." * sp bar += "|" return bar pass
(Googleの文字が出揃うまでどの順番で出てくるのかわからないですが、if条件中の数字を入れ替えればその順で出てくるようになります)
先ほどの例のBarの代わりに、このGoogleBarに入れ替えると色つきで表示されます。