コンソールのテキスト進捗バー[閉じた
質問
次のことをする良い方法はありますか?
FTPLIBを使用してFTPサーバーからファイルをアップロードおよびダウンロードするためのシンプルなコンソールアプリを書きました。
いくつかのデータチャンクがダウンロードされるたびに、たとえそれが単なる数字であっても、テキストの進捗バーを更新したいと思います。
しかし、コンソールに印刷されたすべてのテキストを消去したくありません。 (「クリア」を行い、更新された割合を印刷します。)
解決
シンプルでカスタマイズ可能な進行状況バー
以下の多くの回答の集計を以下に示します。
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
# Print New Line on Complete
if iteration == total:
print()
ノート: これはPython 3用です。 Python 2でこれを使用する詳細については、コメントを参照してください。
サンプルの使用
import time
# A List of Items
items = list(range(0, 57))
l = len(items)
# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
# Do stuff...
time.sleep(0.1)
# Update Progress Bar
printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
サンプル出力:
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
アップデート
コメントで、進行状況バーが端子ウィンドウの幅に動的に調整できるようにするオプションに関する議論がありました。私はこれをお勧めしませんが、ここにあります 要旨 これはこの機能を実装します(および注意事項に注意してください)。
他のヒント
「 r」を書くと、カーソルがラインの先頭に戻ります。
これにより、パーセンテージカウンターが表示されます。
import time
import sys
for i in range(100):
time.sleep(1)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
... time.sleep(1)
...
|###-------| 35/100 35% [elapsed: 00:35 left: 01:05, 1.00 iters/sec]
書く \r
コンソールへ。あれは "キャリッジリターン" これにより、すべてのテキストが行われた後にすべてのテキストが反映されます。何かのようなもの:
def update_progress(progress):
print '\r[{0}] {1}%'.format('#'*(progress/10), progress)
これはあなたに次のようなものを与えます: [ ########## ] 100%
コード10行未満です。
ここの要点: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3
import sys
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
sys.stdout.flush() # As suggested by Rom Ruben
試してみてください クリック PythonのMozartによって書かれた図書館、Armin Ronacher。
$ pip install click # both 2 and 3 compatible
簡単な進行状況バーを作成するには:
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
これがどのように見えるかです:
# [###-------------------------------] 9% 00:01:14
心にカスタマイズするコンテンツ:
import click, sys
with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
for i in bar:
pass
カスタムルック:
(_(_)===================================D(_(_| 100000/100000 00:00:02
さらに多くのオプションがあります APIドキュメント:
click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)
私はゲームに遅れていることに気づきましたが、ここに私が書いたわずかなヤムスタイル(レッドハット)のものがあります(ここでは100%の正確さを求めていませんが、そのレベルの精度に進行状況バーを使用している場合は、あなたは'とにかく間違っています):
import sys
def cli_progress_test(end_val, bar_length=20):
for i in xrange(0, end_val):
percent = float(i) / end_val
hashes = '#' * int(round(percent * bar_length))
spaces = ' ' * (bar_length - len(hashes))
sys.stdout.write("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
sys.stdout.flush()
このように見えるものを生成する必要があります:
Percent: [############## ] 69%
...ブラケットが静止したままで、ハッシュのみが増加します。
これは、装飾器としてよりうまく機能する可能性があります。別の日のために...
これがPythonで書かれたProgressBarの良い例です。 http://nadiana.com/animated-terminal-progress-bar-in-python
しかし、あなたがそれを自分で書きたいなら。使用できます curses
物事を簡単にするモジュール:)
編集]おそらく簡単なのは呪いの言葉ではないでしょう。しかし、呪いよりも本格的なCUIを作成したい場合は、あなたのためにたくさんのものを処理します。
編集]古いリンクが死んでいるので、私は自分のバージョンのPython ProgressBarを掲載しました。 https://github.com/wolph/python-progressbar
import time,sys
for i in range(100+1):
time.sleep(0.1)
sys.stdout.write(('='*i)+(''*(100-i))+("\r [ %d"%i+"% ] "))
sys.stdout.flush()
出力
[ 29% ] ===================
そして、山に追加するために、これがあなたが使用できるオブジェクトです
import sys
class ProgressBar(object):
DEFAULT_BAR_LENGTH = 65
DEFAULT_CHAR_ON = '='
DEFAULT_CHAR_OFF = ' '
def __init__(self, end, start=0):
self.end = end
self.start = start
self._barLength = self.__class__.DEFAULT_BAR_LENGTH
self.setLevel(self.start)
self._plotted = False
def setLevel(self, level):
self._level = level
if level < self.start: self._level = self.start
if level > self.end: self._level = self.end
self._ratio = float(self._level - self.start) / float(self.end - self.start)
self._levelChars = int(self._ratio * self._barLength)
def plotProgress(self):
sys.stdout.write("\r %3i%% [%s%s]" %(
int(self._ratio * 100.0),
self.__class__.DEFAULT_CHAR_ON * int(self._levelChars),
self.__class__.DEFAULT_CHAR_OFF * int(self._barLength - self._levelChars),
))
sys.stdout.flush()
self._plotted = True
def setAndPlot(self, level):
oldChars = self._levelChars
self.setLevel(level)
if (not self._plotted) or (oldChars != self._levelChars):
self.plotProgress()
def __add__(self, other):
assert type(other) in [float, int], "can only add a number"
self.setAndPlot(self._level + other)
return self
def __sub__(self, other):
return self.__add__(-other)
def __iadd__(self, other):
return self.__add__(other)
def __isub__(self, other):
return self.__add__(-other)
def __del__(self):
sys.stdout.write("\n")
if __name__ == "__main__":
import time
count = 150
print "starting things:"
pb = ProgressBar(count)
#pb.plotProgress()
for i in range(0, count):
pb += 1
#pb.setAndPlot(i + 1)
time.sleep(0.01)
del pb
print "done"
結果:
starting things:
100% [=================================================================]
done
これは最も一般的に「上に」あると考えられますが、それをたくさん使っているときは便利です
これを実行します Pythonコマンドラインで (いいえ IDEまたは開発環境で):
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "\r%3d" % i, ('='*i)+('-'*(50-i)),
私のWindowsシステムで正常に動作します。
インストール tqdm
.(pip install tqdm
)そして、次のように使用します。
import time
from tqdm import tqdm
for i in tqdm(range(1000)):
time.sleep(0.01)
これは、このようなものを出力する10秒の進行状況バーです。
47%|██████████████████▊ | 470/1000 [00:04<00:05, 98.61it/s]
- http://code.activestate.com/recipes/168639-progress-bar-class/ (2002)
- http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/ (2004)
- http://pypi.python.org/pypi/progressbar (2006)
そして、グーグルになるのを待っている多くのチュートリアル。
使ってます Redditからの進歩. 。すべてのアイテムの進行状況を1行で印刷できるので、プログラムから印刷物を消去しないため、気に入っています。
編集:リンクを修正しました
上記の回答とCLI Progress Barに関する他の同様の質問に基づいて、私はそれらすべてに一般的な一般的な答えを得たと思います。で確認してください https://stackoverflow.com/a/15860757/2254146
要約すると、コードは次のとおりです。
import time, sys
# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
barLength = 10 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength*progress))
text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status)
sys.stdout.write(text)
sys.stdout.flush()
ように見えます
パーセント:[#########] 99.0%
TQDMを使用することをお勧めします - https://pypi.python.org/pypi/tqdm - これにより、繰り返しやプロセスを進行中のバーに変えることができ、必要な端子をいじっているすべてを処理できます。
ドキュメントから:「TQDMはコールバック/フックと手動の更新を簡単にサポートできます。これがurllibの例です」
import urllib
from tqdm import tqdm
def my_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
Example
-------
>>> with tqdm(...) as t:
... reporthook = my_hook(t)
... urllib.urlretrieve(..., reporthook=reporthook)
"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks just transferred [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
eg_link = 'http://www.doc.ic.ac.uk/~cod11/matryoshka.zip'
with tqdm(unit='B', unit_scale=True, miniters=1,
desc=eg_link.split('/')[-1]) as t: # all optional kwargs
urllib.urlretrieve(eg_link, filename='/dev/null',
reporthook=my_hook(t), data=None)
このパッケージをインストールしてみてください: pip install progressbar2
:
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
ProgressBar Github: https://github.com/wolph/python-progressbar
import sys
def progresssbar():
for i in range(100):
time.sleep(1)
sys.stdout.write("%i\r" % i)
progressbar()
注:これをインタラクティブな交差点で実行すると、追加の数字が印刷されています
笑私はちょうどこれを書いたが、これはコードがブロックasciiを実行するときにUnicodeを使用できないことに留意してください私はCP437を使用します
import os
import time
def load(left_side, right_side, length, time):
x = 0
y = ""
print "\r"
while x < length:
space = length - len(y)
space = " " * space
z = left + y + space + right
print "\r", z,
y += "█"
time.sleep(time)
x += 1
cls()
そして、あなたはそれをそう呼んでいます
print "loading something awesome"
load("|", "|", 10, .01)
だからこのように見えます
loading something awesome
|█████ |
上記の素晴らしいアドバイスで、私は進行状況バーを解決します。
ただし、いくつかの欠点を指摘したいと思います
進行中のバーがフラッシュされるたびに、それは新しいラインで開始されます
print('\r[{0}]{1}%'.format('#' * progress* 10, progress))
このような:
[] 0%
[#]10%
[##]20%
[###]30%
2.四角いブラケット ']'と右側のパーセント数は、「###」が長くなると右にシフトします。
3.「進行状況 / 10」という式が整数を返すことができない場合、エラーが発生します。
また、次のコードでは、上記の問題が修正されます。
def update_progress(progress, total):
print('\r[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')
非常に簡単な解決策は、このコードをループに入れることです。
これをファイルのボディ(つまり上部)に入れます。
import sys
これをループの本体に入れてください:
sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
Pythonターミナルプログレスバーのコード
import sys
import time
max_length = 5
at_length = max_length
empty = "-"
used = "%"
bar = empty * max_length
for i in range(0, max_length):
at_length -= 1
#setting empty and full spots
bar = used * i
bar = bar+empty * at_length
#\r is carriage return(sets cursor position in terminal to start of line)
#\0 character escape
sys.stdout.write("[{}]\0\r".format(bar))
sys.stdout.flush()
#do your stuff here instead of time.sleep
time.sleep(1)
sys.stdout.write("\n")
sys.stdout.flush()
ここで見つけたアイデアのいくつかをまとめ、推定時間を残して追加する:
import datetime, sys
start = datetime.datetime.now()
def print_progress_bar (iteration, total):
process_duration_samples = []
average_samples = 5
end = datetime.datetime.now()
process_duration = end - start
if len(process_duration_samples) == 0:
process_duration_samples = [process_duration] * average_samples
process_duration_samples = process_duration_samples[1:average_samples-1] + [process_duration]
average_process_duration = sum(process_duration_samples, datetime.timedelta()) / len(process_duration_samples)
remaining_steps = total - iteration
remaining_time_estimation = remaining_steps * average_process_duration
bars_string = int(float(iteration) / float(total) * 20.)
sys.stdout.write(
"\r[%-20s] %d%% (%s/%s) Estimated time left: %s" % (
'='*bars_string, float(iteration) / float(total) * 100,
iteration,
total,
remaining_time_estimation
)
)
sys.stdout.flush()
if iteration + 1 == total:
print
# Sample usage
for i in range(0,300):
print_progress_bar(i, 300)
さて、ここに機能するコードがあり、投稿する前にテストしました。
import sys
def prg(prog, fillchar, emptchar):
fillt = 0
emptt = 20
if prog < 100 and prog > 0:
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%")
sys.stdout.flush()
elif prog >= 100:
prog = 100
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nDone!")
sys.stdout.flush()
elif prog < 0:
prog = 0
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nHalted!")
sys.stdout.flush()
長所:
- 20キャラクターバー(5ごとに1文字(数字ごと))
- カスタムフィル文字
- カスタム空の文字
- 停止(0未満の任意の数)
- 完了(100および任意の数値100)
- 進行状況カウント(0-100(特別な機能に使用される以下およびそれ以上))
- バーの隣のパーセンテージ番号、そしてそれは単一の行です
短所:
- 整数のみをサポートします(ただし、部門を整数部門にすることで、それらをサポートするように変更できます。
prog2 = prog/5
にprog2 = int(prog/5)
)
これが私のPython 3ソリューションです:
import time
for i in range(100):
time.sleep(1)
s = "{}% Complete".format(i)
print(s,end=len(s) * '\b')
' b'は、文字列内の各文字のバックスラッシュです。これは、Windows CMDウィンドウ内では機能しません。
2.7のグリーンスティックからの機能:
def printProgressBar (iteration, total, prefix = '', suffix = '',decimals = 1, length = 100, fill = '#'):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print'\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),
sys.stdout.flush()
# Print New Line on Complete
if iteration == total:
print()
Pythonモジュール プログレスバー いい選択です。これが私の典型的なコードです:
import time
import progressbar
widgets = [
' ', progressbar.Percentage(),
' ', progressbar.SimpleProgress(format='(%(value_s)s of %(max_value_s)s)'),
' ', progressbar.Bar('>', fill='.'),
' ', progressbar.ETA(format_finished='- %(seconds)s -', format='ETA: %(seconds)s', ),
' - ', progressbar.DynamicMessage('loss'),
' - ', progressbar.DynamicMessage('error'),
' '
]
bar = progressbar.ProgressBar(redirect_stdout=True, widgets=widgets)
bar.start(100)
for i in range(100):
time.sleep(0.1)
bar.update(i + 1, loss=i / 100., error=i)
bar.finish()
https://pypi.python.org/pypi/progressbar2/3.30.2
ProgressBar2 コマンドラインのインポート時間インポートProgressBarのASCIIベースProgressBarに適したライブラリです
bar = progressbar.ProgressBar()
for i in bar(range(100)):
time.sleep(0.02)
bar.finish()
https://pypi.python.org/pypi/tqdm
TQDM ProgressBar2の代替品であり、PIP3で使用していると思いますが、それはわかりません
from tqdm import tqdm
for i in tqdm(range(10000)):
...
私は単純な進歩を書きました:
def bar(total, current, length=10, prefix="", filler="#", space=" ", oncomp="", border="[]", suffix=""):
if len(border) != 2:
print("parameter 'border' must include exactly 2 symbols!")
return None
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix, "\r", end="")
if total == current:
if oncomp:
print(prefix + border[0] + space * int(((length - len(oncomp)) / 2)) +
oncomp + space * int(((length - len(oncomp)) / 2)) + border[1], suffix)
if not oncomp:
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix)
ご覧のとおり、バー、プレフィックスと接尾辞、フィラー、スペース、100%(ONCOMP)のバーのテキスト、境界線の長さがあります
ここに例:
from time import sleep, time
start_time = time()
for i in range(10):
pref = str((i+1) * 10) + "% "
complete_text = "done in %s sec" % str(round(time() - start_time))
sleep(1)
bar(10, i + 1, length=20, prefix=pref, oncomp=complete_text)
進行中:
30% [###### ]
完全に出て:
100% [ done in 9 sec ]