Gre*_*ick 378
以下是我经常使用的许多答案的汇总.
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '?', printEnd = "\r"):
"""
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)
printEnd - Optional : end character (e.g. "\r", "\r\n") (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 = printEnd)
# Print New Line on Complete
if iteration == total:
print()
Run Code Online (Sandbox Code Playgroud)
样品用法:
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)
Run Code Online (Sandbox Code Playgroud)
样本输出:
Progress: |?????????????????????????????????????????????-----| 90.0% Complete
Run Code Online (Sandbox Code Playgroud)
Ste*_*hen 298
写'\ r'会将光标移回到行的开头.
这显示一个百分比计数器:
import time
import sys
for i in range(100):
time.sleep(1)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 165
>>> 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]
Run Code Online (Sandbox Code Playgroud)
avi*_*ldg 109
写一个\r
到控制台.这是一个"回车",它会导致它后面的所有文本在行的开头回显.就像是:
def update_progress(progress):
print '\r[{0}] {1}%'.format('#'*(progress/10), progress)
Run Code Online (Sandbox Code Playgroud)
这将给你类似的东西: [ ########## ] 100%
Vla*_*yev 67
它不到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
Run Code Online (Sandbox Code Playgroud)
The*_*Cat 58
试试由Mozart of Python,Armin Ronacher编写的点击库.
$ pip install click # both 2 and 3 compatible
Run Code Online (Sandbox Code Playgroud)
要创建一个简单的进度条:
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
Run Code Online (Sandbox Code Playgroud)
这就是它的样子:
# [###-------------------------------] 9% 00:01:14
Run Code Online (Sandbox Code Playgroud)
根据您的心灵内容定制:
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
Run Code Online (Sandbox Code Playgroud)
自定义外观:
(_(_)===================================D(_(_| 100000/100000 00:00:02
Run Code Online (Sandbox Code Playgroud)
还有更多选项,请参阅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)
Run Code Online (Sandbox Code Playgroud)
Joe*_*nux 32
我意识到我已经迟到了,但是这里有一个我写的略带百胜风格(Red Hat)(这里不是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()
Run Code Online (Sandbox Code Playgroud)
应该产生这样的东西:
Percent: [############## ] 69%
Run Code Online (Sandbox Code Playgroud)
......托架保持静止,只有哈希增加.
这可能更适合作为装饰者.再过一天......
scr*_*pts 17
检查这个库:clint
它有很多功能,包括进度条:
from time import sleep
from random import random
from clint.textui import progress
if __name__ == '__main__':
for i in progress.bar(range(100)):
sleep(random() * 0.2)
for i in progress.dots(range(100)):
sleep(random() * 0.2)
Run Code Online (Sandbox Code Playgroud)
此链接提供其功能的快速概述
Wol*_*lph 12
这是一个用Python编写的进度条的一个很好的例子:http://nadiana.com/animated-terminal-progress-bar-in-python
但如果你想自己写.您可以使用该curses
模块使事情变得更容易:)
[编辑]也许更容易的不是诅咒这个词.但如果你想创造一个完整的cui而不是curses为你照顾很多东西.
[编辑]由于旧的链接已经死了,我已经提出了我自己的Python Progressbar版本,请点击此处:https://github.com/WoLpH/python-progressbar
ash*_*2py 11
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()
Run Code Online (Sandbox Code Playgroud)
产量
[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"
Run Code Online (Sandbox Code Playgroud)
结果是:
starting things:
100% [=================================================================]
done
Run Code Online (Sandbox Code Playgroud)
这通常被认为是"超过顶部",但是当你经常使用它时它很方便
在Python命令行(不在任何IDE或开发环境中)运行此命令:
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "\r%3d" % i, ('='*i)+('-'*(50-i)),
Run Code Online (Sandbox Code Playgroud)
在我的Windows系统上正常工作.
小智 6
安装tqdm
.(pip install tqdm
)并按如下方式使用它:
import time
from tqdm import tqdm
for i in tqdm(range(1000)):
time.sleep(0.01)
Run Code Online (Sandbox Code Playgroud)
这是一个10秒的进度条,它会输出这样的东西:
47%|??????????????????? | 470/1000 [00:04<00:05, 98.61it/s]
Run Code Online (Sandbox Code Playgroud)
小智 6
尝试安装这个包 pip install progressbar2
::
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
Run Code Online (Sandbox Code Playgroud)
进度条 github:https : //github.com/WoLpH/python-progressbar
小智 5
一个非常简单的解决方案是将以下代码放入循环中:
将其放入文件的正文(即顶部)中:
import sys
Run Code Online (Sandbox Code Playgroud)
将其放入循环体中:
sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
289804 次 |
最近记录: |