[英]Python Progress Bar
当我的脚本正在执行一些可能需要时间的任务时,如何使用进度条?
例如,一个 function 需要一些时间才能完成并在完成时返回True
。 如何在执行 function 期间显示进度条?
请注意,我需要它是实时的,所以我不知道该怎么做。 我需要一个thread
吗? 我不知道。
现在在执行 function 时我没有打印任何东西,但是进度条会很好。 此外,我对如何从代码的角度完成此操作更感兴趣。
使用tqdm ( conda install tqdm
或pip install tqdm
),您可以在一秒钟内将进度表添加到您的循环中:
from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
sleep(3)
60%|██████ | 6/10 [00:18<00:12, 0.33 it/s]
此外,还有一个笔记本版本:
from tqdm.notebook import tqdm
for i in tqdm(range(100)):
sleep(3)
您可以使用tqdm.auto
而不是tqdm.notebook
在终端和笔记本中工作。
tqdm.contrib
包含一些辅助函数来执行诸如enumerate
、 map
和zip
之类的操作。 tqdm.contrib.concurrent
中有并发映射。
使用tqdm.contrib.telegram
或tqdm.contrib.discord
断开与 jupyter notebook 的连接后,您甚至可以将进度发送到您的手机。
有特定的库(比如这里的这个),但也许可以做一些非常简单的事情:
import time
import sys
toolbar_width = 40
# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['
for i in xrange(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("]\n") # this ends the progress bar
注意: progressbar2是一个多年未维护的进度条的分支。
使用alive-progress ,有史以来最酷的进度条!
要以有用的方式使用任何进度条框架,即获得完成百分比和预计到达时间 (ETA),您需要能够知道您的处理将有多少个步骤。
然后你可以插入一个yield
来标记一个项目已被处理,你就可以开始了!
def compute():
for i in range(1000):
... # process items as usual.
yield # insert this :)
然后像这样使用它:
from alive_progress import alive_bar
with alive_bar(1000) as bar:
for i in compute():
bar()
获得一个真棒和生动的进度条!
|█████████████▎ | ▅▃▁ 321/1000 [32%] in 8s (40.1/s, eta: 16s)
披露:我是alive-progress
的作者,但它应该可以很好地解决您的问题! 阅读https://github.com/rsalmei/alive-progress上的文档以了解更多信息。 现在它也适用于 Jupyter Notebooks! 以下是它可以做什么的更多示例:
您可以自定义栏进度符号"#"
、栏size
、文本prefix
等。
import sys
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.3+
count = len(it)
def show(j):
x = int(size*j/count)
print("{}[{}{}] {}/{}".format(prefix, "#"*x, "."*(size-x), j, count),
end='\r', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("\n", flush=True, file=out)
import time
for i in progressbar(range(15), "Computing: ", 40):
time.sleep(0.1) # any code you need
要填充整个字符空间,请使用 unicode u"█"
char 替换"#"
。 随着for i in progressbar(range(100)): ...
你得到:
不需要第二个线程。 上面的一些解决方案/包需要。
适用于任何可迭代对象,这意味着可以使用len()
的任何对象。 一个list
,任何东西的dict
,例如['a', 'b', 'c' ... 'g']
与生成器一起工作只需要用 list() 包装它。 例如for i in progressbar(list(your_generator), "Computing: ", 40):
除非工作是在生成器中完成的。 在这种情况下,您需要另一种解决方案(如 tqdm) 。
例如,您还可以通过更改为sys.stderr
来更改out
。
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.6+
count = len(it)
def show(j):
x = int(size*j/count)
print(f"{prefix}[{u'█'*x}{('.'*(size-x))}] {j}/{count}", end='\r', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("\n", flush=True, file=out)
import sys
def progressbar(it, prefix="", size=60, out=sys.stdout):
count = len(it)
def show(j):
x = int(size*j/count)
out.write("%s[%s%s] %i/%i\r" % (prefix, u"#"*x, "."*(size-x), j, count))
out.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
out.write("\n")
out.flush()
上面的建议都不错,但我想大多数人只是想要一个现成的解决方案,不依赖外部包,但也可以重用。
我得到了以上所有优点,并将其与测试用例一起制作成一个函数。
要使用它,只需复制“def update_progress(progress)”下的行,而不是测试脚本。 不要忘记导入 sys. 每当您需要显示或更新进度条时调用它。
这通过直接将“\r”符号发送到控制台以将光标移回开头来工作。 python中的“print”没有为此目的识别上述符号,因此我们需要“sys”
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()
# update_progress test script
print "progress : 'hello'"
update_progress("hello")
time.sleep(1)
print "progress : 3"
update_progress(3)
time.sleep(1)
print "progress : [23]"
update_progress([23])
time.sleep(1)
print ""
print "progress : -10"
update_progress(-10)
time.sleep(2)
print ""
print "progress : 10"
update_progress(10)
time.sleep(2)
print ""
print "progress : 0->1"
for i in range(101):
time.sleep(0.1)
update_progress(i/100.0)
print ""
print "Test completed"
time.sleep(10)
这是测试脚本的结果显示(最后一个进度条动画):
progress : 'hello'
Percent: [----------] 0% error: progress var must be float
progress : 3
Percent: [##########] 100% Done...
progress : [23]
Percent: [----------] 0% error: progress var must be float
progress : -10
Percent: [----------] 0% Halt...
progress : 10
Percent: [##########] 100% Done...
progress : 0->1
Percent: [##########] 100% Done...
Test completed
从https://pypi.python.org/pypi/progress尝试进度。
from progress.bar import Bar
bar = Bar('Processing', max=20)
for i in range(20):
# Do some work
bar.next()
bar.finish()
结果将是如下所示的条形图:
Processing |############# | 42/100
对于类似的应用程序(循环跟踪进度),我只是使用了python-progressbar :
他们的例子是这样的,
from progressbar import * # just a simple progress bar
widgets = ['Test: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),
' ', ETA(), ' ', FileTransferSpeed()] #see docs for other options
pbar = ProgressBar(widgets=widgets, maxval=500)
pbar.start()
for i in range(100,500+1,50):
# here do something long at each iteration
pbar.update(i) #this adds a little symbol at each iteration
pbar.finish()
print
在此处搜索等效解决方案后,我刚刚为我的需要制作了一个简单的进度类。 我想我可能会很好地发布它。
from __future__ import print_function
import sys
import re
class ProgressBar(object):
DEFAULT = 'Progress: %(bar)s %(percent)3d%%'
FULL = '%(bar)s %(current)d/%(total)d (%(percent)3d%%) %(remaining)d to go'
def __init__(self, total, width=40, fmt=DEFAULT, symbol='=',
output=sys.stderr):
assert len(symbol) == 1
self.total = total
self.width = width
self.symbol = symbol
self.output = output
self.fmt = re.sub(r'(?P<name>%\(.+?\))d',
r'\g<name>%dd' % len(str(total)), fmt)
self.current = 0
def __call__(self):
percent = self.current / float(self.total)
size = int(self.width * percent)
remaining = self.total - self.current
bar = '[' + self.symbol * size + ' ' * (self.width - size) + ']'
args = {
'total': self.total,
'bar': bar,
'current': self.current,
'percent': percent * 100,
'remaining': remaining
}
print('\r' + self.fmt % args, file=self.output, end='')
def done(self):
self.current = self.total
self()
print('', file=self.output)
例子 :
from time import sleep
progress = ProgressBar(80, fmt=ProgressBar.FULL)
for x in xrange(progress.total):
progress.current += 1
progress()
sleep(0.1)
progress.done()
将打印以下内容:
[======== ] 17/80 ( 21%) 63 to go
您可以使用tqdm :
from tqdm import tqdm
with tqdm(total=100, desc="Adding Users", bar_format="{l_bar}{bar} [ time left: {remaining} ]") as pbar:
for i in range(100):
time.sleep(3)
pbar.update(1)
在此示例中,进度条运行了 5 分钟,如下所示:
Adding Users: 3%|█████▊ [ time left: 04:51 ]
您可以根据需要更改和自定义它。
我喜欢Brian Khuu 的答案,因为它简单且不需要外部软件包。 我改变了一点,所以我在这里添加我的版本:
import sys
import time
def updt(total, progress):
"""
Displays or updates a console progress bar.
Original source: https://stackoverflow.com/a/15860757/1391441
"""
barLength, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(barLength * progress))
text = "\r[{}] {:.0f}% {}".format(
"#" * block + "-" * (barLength - block), round(progress * 100, 0),
status)
sys.stdout.write(text)
sys.stdout.flush()
runs = 300
for run_num in range(runs):
time.sleep(.1)
updt(runs, run_num + 1)
假设total >= progress
,它需要运行总数 ( total
) 和到目前为止处理的运行数 ( progress
)。 结果如下所示:
[#####---------------] 27%
我真的很喜欢python-progressbar ,因为它使用起来非常简单。
对于最简单的情况,它只是:
import progressbar
import time
progress = progressbar.ProgressBar()
for i in progress(range(80)):
time.sleep(0.01)
外观可定制,可显示预计剩余时间。 例如,使用与上面相同的代码,但具有:
progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',
progressbar.Percentage(), ' ',
progressbar.ETA()])
如果它是一个具有固定迭代次数的大循环,需要花费大量时间,您可以使用我制作的这个函数。 循环的每次迭代都会增加进度。 其中 count 是循环的当前迭代,total 是您要循环到的值,而 size(int) 是您希望条形以 10 为增量的大小,即(大小 1 =10 个字符,大小 2 =20 个字符)
import sys
def loadingBar(count,total,size):
percent = float(count)/float(total)*100
sys.stdout.write("\r" + str(int(count)).rjust(3,'0')+"/"+str(int(total)).rjust(3,'0') + ' [' + '='*int(percent/10)*size + ' '*(10-int(percent/10))*size + ']')
例子:
for i in range(0,100):
loadingBar(i,100,2)
#do some code
输出:
i = 50
>> 050/100 [========== ]
一个简单的oneliner:
K = 628318
for k in range(K):
# your stuff
print(end="\r|%-80s|" % ("="*int(80*k/(K-1))))
|===================================================================== |
80是条的长度。 最终你想要一个最终的print()
。
不要忘记数字进度指示器:
K = 628318
for k in range(K):
# your stuff
print(end="\r%6.2f %%" % (k/(K-1)*100))
94.53 %
如果需要,将两者结合起来并不难。
关键是“回车” \r
和print
中默认end="\n"
的抑制。
18% |████▌ | \ [0:00:01, 0:00:06]
在 Python3 中非常简单:
import time
import math
def show_progress_bar(bar_length, completed, total):
bar_length_unit_value = (total / bar_length)
completed_bar_part = math.ceil(completed / bar_length_unit_value)
progress = "*" * completed_bar_part
remaining = " " * (bar_length - completed_bar_part)
percent_done = "%.2f" % ((completed / total) * 100)
print(f'[{progress}{remaining}] {percent_done}%', end='\r')
bar_length = 30
total = 100
for i in range(0, total + 1):
show_progress_bar(bar_length, i, total)
time.sleep(0.1)
print('\n')
在 jupyter 笔记本中运行时,使用普通 tqdm 不起作用,因为它会在多行上写入输出。 改用这个:
import time
from tqdm import tqdm_notebook as tqdm
for i in tqdm(range(100))
time.sleep(0.5)
我喜欢这个页面。
从简单的示例开始,然后转到多线程版本。 开箱即用。 不需要第 3 方包。
代码将如下所示:
import time
import sys
def do_task():
time.sleep(1)
def example_1(n):
for i in range(n):
do_task()
print '\b.',
sys.stdout.flush()
print ' Done!'
print 'Starting ',
example_1(10)
或者这里是使用线程以在程序运行时运行旋转加载栏的示例:
import sys
import time
import threading
class progress_bar_loading(threading.Thread):
def run(self):
global stop
global kill
print 'Loading.... ',
sys.stdout.flush()
i = 0
while stop != True:
if (i%4) == 0:
sys.stdout.write('\b/')
elif (i%4) == 1:
sys.stdout.write('\b-')
elif (i%4) == 2:
sys.stdout.write('\b\\')
elif (i%4) == 3:
sys.stdout.write('\b|')
sys.stdout.flush()
time.sleep(0.2)
i+=1
if kill == True:
print '\b\b\b\b ABORT!',
else:
print '\b\b done!',
kill = False
stop = False
p = progress_bar_loading()
p.start()
try:
#anything you want to run.
time.sleep(1)
stop = True
except KeyboardInterrupt or EOFError:
kill = True
stop = True
这是一个以编程方式构建加载栏的简短解决方案(您必须决定需要多长时间)。
import time
n = 33 # or however many loading slots you want to have
load = 0.01 # artificial loading time!
loading = '.' * n # for strings, * is the repeat operator
for i in range(n+1):
# this loop replaces each dot with a hash!
print('\r%s Loading at %3d percent!' % (loading, i*100/n), end='')
loading = loading[:i] + '#' + loading[i+1:]
time.sleep(load)
if i==n: print()
我使用format()
方法制作了一个加载栏。 这是我的解决方案:
import time
loadbarwidth = 23
for i in range(1, loadbarwidth + 1):
time.sleep(0.1)
strbarwidth = '[{}{}] - {}\r'.format(
(i * '#'),
((loadbarwidth - i) * '-'),
(('{:0.2f}'.format(((i) * (100/loadbarwidth))) + '%'))
)
print(strbarwidth ,end = '')
print()
输出:
[#######################] - 100.00%
没有外部库的简单进度条的2022答案
import time, sys
def progress(size):
for item in range(size):
if(item==0):
print("[",end="")
elif(item==size-1):
print("]",end="\n")
else:
#main work goes here
time.sleep(0.1)
print("%",end="")
sys.stdout.flush()
progress(50)
如果你的工作不能被分解成可测量的块,你可以在一个新线程中调用你的函数并计算它需要多长时间:
import thread
import time
import sys
def work():
time.sleep( 5 )
def locked_call( func, lock ):
lock.acquire()
func()
lock.release()
lock = thread.allocate_lock()
thread.start_new_thread( locked_call, ( work, lock, ) )
# This part is icky...
while( not lock.locked() ):
time.sleep( 0.1 )
while( lock.locked() ):
sys.stdout.write( "*" )
sys.stdout.flush()
time.sleep( 1 )
print "\nWork Done"
您显然可以根据需要提高计时精度。
我喜欢加布里埃尔的回答,但我把它改成了灵活的。 您可以将 bar-length 发送到该函数并获得您想要的任何长度的进度条。 而且你不能有一个零长度或负长度的进度条。 此外,您可以使用此功能,如Gabriel answer(请参阅示例 #2)。
import sys
import time
def ProgressBar(Total, Progress, BarLength=20, ProgressIcon="#", BarIcon="-"):
try:
# You can't have a progress bar with zero or negative length.
if BarLength <1:
BarLength = 20
# Use status variable for going to the next line after progress completion.
Status = ""
# Calcuting progress between 0 and 1 for percentage.
Progress = float(Progress) / float(Total)
# Doing this conditions at final progressing.
if Progress >= 1.:
Progress = 1
Status = "\r\n" # Going to the next line
# Calculating how many places should be filled
Block = int(round(BarLength * Progress))
# Show this
Bar = "[{}] {:.0f}% {}".format(ProgressIcon * Block + BarIcon * (BarLength - Block), round(Progress * 100, 0), Status)
return Bar
except:
return "ERROR"
def ShowBar(Bar):
sys.stdout.write(Bar)
sys.stdout.flush()
if __name__ == '__main__':
print("This is a simple progress bar.\n")
# Example #1:
print('Example #1')
Runs = 10
for i in range(Runs + 1):
progressBar = "\rProgress: " + ProgressBar(10, i, Runs)
ShowBar(progressBar)
time.sleep(1)
# Example #2:
print('\nExample #2')
Runs = 10
for i in range(Runs + 1):
progressBar = "\rProgress: " + ProgressBar(10, i, 20, '|', '.')
ShowBar(progressBar)
time.sleep(1)
print('\nDone.')
# Example #2:
Runs = 10
for i in range(Runs + 1):
ProgressBar(10, i)
time.sleep(1)
结果:
这是一个简单的进度条。
示例 #1
进度:[###-------] 30%
示例 #2
进度:[||||||||||||........] 60%
完毕。
猜我有点晚了,但这应该适用于使用当前版本的 python 3的人,因为它使用 Python 3.6 PEP 498中介绍的“f-strings” :
代码
from numpy import interp
class Progress:
def __init__(self, value, end, title='Downloading',buffer=20):
self.title = title
#when calling in a for loop it doesn't include the last number
self.end = end -1
self.buffer = buffer
self.value = value
self.progress()
def progress(self):
maped = int(interp(self.value, [0, self.end], [0, self.buffer]))
print(f'{self.title}: [{"#"*maped}{"-"*(self.buffer - maped)}]{self.value}/{self.end} {((self.value/self.end)*100):.2f}%', end='\r')
例子
#some loop that does perfroms a task
for x in range(21) #set to 21 to include until 20
Progress(x, 21)
输出
Downloading: [########------------] 8/20 40.00%
使用进度库!
pip install progress
这是我编写的一个自定义子类,用于将 ETA/Elapsed 时间格式化为可读性更好的格式:
import datetime
from progress.bar import IncrementalBar
class ProgressBar(IncrementalBar):
'''
My custom progress bar that:
- Show %, count, elapsed, eta
- Time is shown in H:M:S format
'''
message = 'Progress'
suffix = '%(percent).1f%% (%(index)d/%(max)d) -- %(elapsed_min)s (eta: %(eta_min)s)'
def formatTime(self, seconds):
return str(datetime.timedelta(seconds=seconds))
@property
def elapsed_min(self):
return self.formatTime(self.elapsed)
@property
def eta_min(self):
return self.formatTime(self.eta)
if __name__=='__main__':
counter = 120
bar = ProgressBar('Processing', max=counter)
for i in range(counter):
bar.next()
time.sleep(1)
bar.finish()
这是我的简单解决方案:
import time
def progress(_cur, _max):
p = round(100*_cur/_max)
b = f"Progress: {p}% - ["+"."*int(p/5)+" "*(20-int(p/5))+"]"
print(b, end="\r")
# USAGE:
for i in range(0,101):
time.sleep(0.1)
progress(i,100)
print("..."*5, end="\r")
print("Done")
一个非常简单的方法:
def progbar(count: int) -> None:
for i in range(count):
print(f"[{i*'#'}{(count-1-i)*' '}] - {i+1}/{count}", end="\r")
yield i
print('\n')
以及用法:
from time import sleep
for i in progbar(10):
sleep(0.2) #whatever task you need to do
试试 PyProg。 PyProg 是一个用于 Python 的开源库,用于创建超级可定制的进度指示器和条形图。
当前版本为 1.0.2; 它托管在 Github 上并在 PyPI 上可用(链接如下)。 它与 Python 3 & 2 兼容,也可以与 Qt 控制台一起使用。
它真的很容易使用。 以下代码:
import pyprog
from time import sleep
# Create Object
prog = pyprog.ProgressBar(" ", "", 34)
# Update Progress Bar
prog.update()
for i in range(34):
# Do something
sleep(0.1)
# Set current status
prog.set_stat(i + 1)
# Update Progress Bar again
prog.update()
# Make the Progress Bar final
prog.end()
将产生:
Initial State:
Progress: 0% --------------------------------------------------
When half done:
Progress: 50% #########################-------------------------
Final State:
Progress: 100% ##################################################
我实际上制作了 PyProg,因为我需要一个简单但超级可定制的进度条库。 您可以使用以下命令轻松安装它: pip install pyprog
。
PyProg Github: https ://github.com/Bill13579/pyprog
皮皮: https ://pypi.python.org/pypi/pyprog/
您也可以使用启蒙。 主要优点是您可以同时登录而不会覆盖进度条。
import time
import enlighten
manager = enlighten.Manager()
pbar = manager.counter(total=100)
for num in range(1, 101):
time.sleep(0.05)
print('Step %d complete' % num)
pbar.update()
它还处理多个进度条。
import time
import enlighten
manager = enlighten.Manager()
odds = manager.counter(total=50)
evens = manager.counter(total=50)
for num in range(1, 101):
time.sleep(0.05)
if num % 2:
odds.update()
else:
evens.update()
jelde015的一个更通用的答案(当然归功于他)
手动更新加载栏将是:
import sys
from math import *
def loadingBar(i, N, size):
percent = float(i) / float(N)
sys.stdout.write("\r"
+ str(int(i)).rjust(3, '0')
+"/"
+str(int(N)).rjust(3, '0')
+ ' ['
+ '='*ceil(percent*size)
+ ' '*floor((1-percent)*size)
+ ']')
并通过以下方式调用它:
loadingBar(7, 220, 40)
将导致:
007/220 [= ]
只要你想用当前的i
值调用它。
将size
设置为条形应为的字符数
我使用 wget,如果在 mac 或 linux 上,您必须在 windows 或终端的 cmd 提示符下安装模块
pip install wget
这很简单,只需使用 download() 函数
import wget
url = input("Enter Url to download: ")
wget.download(url)
tqdm 也是一个选项,你也必须下载模块。
pip install tqdm
现在确保导入模块,设置范围并通过
from tqdm import tqdm
for i in tqdm(range(int(9e7))):
pass
已经有很多惊人的答案了,我想分享我对进度条的解决方案。
from time import sleep
def progress_bar(progress: float, total: float, width: int = 25):
percent = width * ((progress + 1) / total)
bar = chr(9608) * int(percent) + "-" * (width - int(percent))
print(f"\r|{bar}| {(100/width)*percent:.2f}%", end="\r")
numbers = range(0, 1000)
numbersLen = len(numbers)
for i in numbers:
sleep(0.01) # Do something usefull here
progress_bar(i, numbersLen)
编辑:
如果您正在寻找一个可以根据终端的宽度调整它的条形图,并且最后可能会出现消息,那么这也可以。 请注意,如果终端变得太窄,则该消息将消失,因为如果它对于 1 行来说太宽,则条将中断。
def progressBar(progress: float, total: float, message: str = ""):
terminalWidth = get_terminal_size().columns
width = int(terminalWidth / 4)
percent = width * ((progress + 1) / total)
bar = chr(9608) * int(percent) + "-" * (width - int(percent))
if terminalWidth <= 40:
message = ""
else:
message = message + (" " * (int(terminalWidth / 2) - len(message)))
print(f"\r|{bar}| {(100/width)*percent:.2f}% " + message, end="\r")
已经有很多好的分析器了,但是根据@HandyGold75 的答案添加这个特定的,我希望它在特定的上下文中被调用,带有初始的消息,加上最后几秒钟的时间反馈。
from time import sleep, time
class ProgressBar:
def __init__(self, total: float, width: int = 50, msg: str = ""):
self.total = total
self.width = width
self.start: float = time()
if msg:
print(f"{msg}")
def progress(self, progress: float):
percent = self.width * ((progress) / self.total)
bar = chr(9608) * int(percent) + "-" * (self.width - int(percent))
print(
f"\r|{bar}| {(100/self.width)*percent:.2f}% "
f"[{progress} of {self.total}]",
end="\r",
)
def __enter__(self):
return self.progress
def __exit__(self, type, value, traceback):
end: float = time()
print(f"\nFinished after {end - self.start: .3f} seconds.")
# USAGE
total_loops = 150
with ProgressBar(total=total_loops) as progress:
for i in range(total_loops):
sleep(0.01) # Do something usefull here
progress(i + 1)
@Massagran:它在我的程序中运行良好。 此外,我们需要添加一个计数器来指示循环时间。 此计数器用作方法update
的参数。 例如:读取测试文件的所有行并将它们处理为某事。 假设函数dosth()
与变量i
无关。
lines = open(sys.argv[1]).readlines()
i = 0
widgets=[Percentage(), Bar()]
pbar = ProgressBar(widgets=widgets,maxval=len(lines)).start()
pbar.start()
for line in lines:<pre>
dosth();
i += 1
pbar.update(i)</pre>
pbar.finish()
变量i
通过方法update
控制pbar
的状态
您应该将进度条链接到手头的任务(以便它衡量进度:D)。 例如,如果您正在通过 FTP 传输文件,您可以告诉 ftplib 获取某个大小的缓冲区,比如说 128K,然后您将 128k 代表的文件大小百分比添加到进度条。 如果您使用的是 CLI,并且您的进度条有 20 个字符长,那么您将在文件传输 1/20 时添加一个字符。
使用os_sys库:
我将它用于多种类型的酒吧,例如:
from os_sys.progress import bar as Bar
bar = Bar('progresing: ', max=20)
for i in range(20):
#do somthing
bar.next()
bar.finish()
你的输出将是:
procesing: |###### | 2/10
在 os_sys 的描述中阅读更多内容
这是创建进度条的简单方法
import time,sys
toolbar_width = 50
# setting up toolbar [-------------------------------------]
sys.stdout.write("[%s]"%(("-")*toolbar_width))
sys.stdout.flush()
# each hash represents 2 % of the progress
for i in range(toolbar_width):
sys.stdout.write("\r") # return to start of line
sys.stdout.flush()
sys.stdout.write("[")#Overwrite over the existing text from the start
sys.stdout.write("#"*(i+1))# number of # denotes the progress completed
sys.stdout.flush()
time.sleep(0.1)
此进度条显示每完成 2% 的分数和每完成 10% 的数字。
import sys
def ProgressBar (num, total, nextPercent, nextPoint):
num = float (num)
total = float (total) - 1
if not nextPoint:
nextPoint = 0.0
if not nextPercent:
nextPoint += 2.0
sys.stdout.write ("[0%")
nextPercent = 10
elif num == total:
sys.stdout.write ("100%]\n")
nextPercent += 10
elif not nextPoint:
nextPoint = 0.0
elif num / total * 100 >= nextPercent:
sys.stdout.write (str(int (nextPercent)) + "%")
nextPercent += 10
elif num / total * 100 >= nextPoint:
sys.stdout.write (":")
nextPoint += 2
return (nextPercent, nextPoint)
nextPercent, nextPoint = 0, 0
total = 1000
for num in range (total):
nextPercent, nextPoint = ProgressBar (num, total, nextPercent, nextPoint)
结果:
>>>
[0%::::10%:::::20%:::::30%:::::40%:::::50%:::::60%:::::70%:::::80%:::::90%:::::100%]
>>>
这里有一个简单的解决方案!
void = '-'
fill = '#'
count = 100/length
increaseCount = 0
for i in range(length):
print('['+(fill*i)+(void*(length-i))+'] '+str(int(increaseCount))+'%',end='\r')
increaseCount += count
time.sleep(0.1)
print('['+(fill*(i+1))+(void*(length-(i+1)))+'] '+str(int(increaseCount))+'%',end='\n')
注意:您可以根据需要修改填充和“空白”字符。
iterrows 的进度条。 @eubrasileiro 代码的改编,用于在循环遍历数据帧的行时显示进度。 此外还显示百分比、第 i 个/计数、经过的秒数、迭代次数/秒、剩余秒数。 允许指定第 n 个更新计数(每)。
import time
import sys
def progressbar_iterrows(df, prefix="", size=60, file=sys.stdout, per=1000):
count = len(df)
t = 0
def show(j,elapsed):
avg = 0 if elapsed == 0 else j/elapsed
remaining = 0 if avg == 0 else (count-j)/avg
x = int(size*j/count)
file.write("%s[%s%s] %i%% %i/%i elapsed:%i %i/sec remaining:%i\r" % (prefix, "#"*x, "."*(size-x), j/count, j, count, elapsed, avg, remaining))
file.flush()
file.write("Initializing ...\r")
file.flush()
for i, item in df.iterrows():
yield i,item
if t == 0:
t = time.time()
if i % per == 0:
show(i,time.time()-t)
file.write("\n")
file.flush()
用法:
for n,r in progressbar_iterrows(br_b_sections_df, "Processed: "):
# do something
输出:
Processed: [........................] 0% 5000/28751240 elapsed:12 413/sec remaining:55054
from IPython.display import clear_output
progress_bar=u"\u001b[7m Loading: "
for i in range(100):
clear_output(wait=True)
progress_bar+=u"\u001b[7m "
print(progress_bar+str(i+1)+"%")
time.sleep(0.03) #you can change the speed
发布的答案都没有完全满足我的需求。 所以我写了我自己的,如上图所示。 我需要的功能:
调用进度显示非常简单。 对于上面的示例.gif
,使用以下方法调用该函数:
percent_complete(step, total_steps, title="Convert Markdown")
CSV 格式的 Stack Exchange 数据转储中len(rows)
的total_steps
约为 2,500。 该step
是当前行号,因为每个 Stack Exchange Markdown Q&A 都被转换为 Kramdown(用于 GitHub 页面)。
代码很简单,但比其他答案长一点:
def percent_complete(step, total_steps, bar_width=60, title="", print_perc=True):
import sys
fill = "▒" # Fill up to bar_width
utf_8s = ["▉", "▎", "▌", "▊"] # UTF-8 left blocks: 7/8, 1/4, 1/2, 3/4
perc = 100 * float(step) / float(total_steps)
max_ticks = bar_width * 4
num_ticks = int(round(perc / 100 * max_ticks))
full_ticks = num_ticks / 4 # Number of full blocks
part_ticks = num_ticks % 4 # Size of partial block (array index)
disp = bar = "" # Blank out variables
bar += utf_8s[0] * full_ticks # Add full blocks into Progress Bar
# If part_ticks is zero, then no partial block, else append part char
if part_ticks > 0:
bar += utf_8s[part_ticks]
# Pad Progress Bar with fill character
bar += fill * int((max_ticks/4 - float(num_ticks)/4.0))
if len(title) > 0:
disp = title + ": " # Optional title to progress display
disp += bar # Progress bar to progress display
if print_perc:
# If requested, append percentage complete to progress display
if perc > 100.0:
perc = 100.0 # Fix "100.04 %" rounding error
disp += " {:6.2f}".format(perc) + " %"
# Output to terminal repetitively over the same line using '\r'.
sys.stdout.write("\r" + disp)
sys.stdout.flush()
几点:
[ .... ]
括号占位符不是必需的,因为存在用于相同目的的填充字符。 这会节省两个额外的字符,使进度条变宽。bar_width
关键字参数可以根据屏幕宽度使用。 默认值60
似乎适合大多数用途。print_perc=False
来覆盖print_perc=True
关键字参数默认值。 这将允许更长的进度条。title=""
关键字参数默认为无标题。 如果您希望使用title="My Title"
并且:
将自动添加到其中。sys.stdout.write("\\r")
后跟sys.stdout.flush()
以清除进度显示行。这个答案比其他答案要长一些,但重要的是要注意它是一个完整的解决方案,而不是您需要添加更多代码的解决方案的一部分。
另一点是这个解决方案没有依赖项,也不需要安装任何额外的东西。 Python 支持 UTF-8 字符集,不需要额外设置gnome-terminal
。 如果您使用的是 Python 2.7,您可能需要# -*- coding: utf-8 -*-
在 shebang 之后。 IE 作为程序的第二行。
该函数可以转换为具有单独init
、 update
、 pause
(用于将调试内容打印到屏幕)、 resume
和close
方法的类。
此函数是从 bash 脚本转换而来的。 每当电视音量发生变化时,bash 脚本都会使用libnotify-bin
(弹出气泡消息)显示索尼电视音量。 如果您对 bash 版本感兴趣,请在下面发表评论。
#doesnt affect actual execution
#based on events and consumption in background
#may be that actual process completes a bit earlier than progress shows 99%
#make an instance with number of elements in a loop
#in each iteration call the method current_progress
import time
from math import ceil
import os
import sys
from threading import Thread
class progress_bar(object):
def __init__(self,total_elements,length_bar=25):
self.length_bar=length_bar
self.total_elements=total_elements
self.singleweight=(float(1)/float(total_elements))*100
self.done=0
self.qt=[0]
self.call_count=0
t=Thread(target=self.display_progress)
t.start()
def current_progress(self):
self.done+=1
self.qt=[self.done]+self.qt
def display_progress(self):
while True:
try:
done=self.qt.pop()
except:
continue
else:
self.call_count+=1
self.progress=self.singleweight*done
fill=ceil(self.progress)
bar=int((fill*self.length_bar)/100)*"|"
bar="["+bar+str(fill)+"%"
barp=bar
for i in range(0,self.length_bar+3-(len(bar))):
barp=barp+"_"
barp=barp+"]"
if self.progress <= 100:
os.system("clear")
print("Progress:",barp, sep=' ', end='\n', file=sys.stdout, flush=True)
if self.call_count == self.total_elements:
break
else:
pass
受到许多没有 package 依赖的答案的启发,我在这里分享我的实现。 用于任何循环的 function 需要当前迭代次数、迭代总数和初始时间。
import time
def simple_progress_bar(i: int, n: int, init_time: float):
avg_time = (time.time()-init_time)/(i+1)
percent = ((i+1)/(n))*100
print(
end=f"\r|{'='*(int(percent))+'>'+'.'*int(100-int(percent))}|| " + \
f"||Completion: {percent : 4.3f}% || \t "+ \
f"||Time elapsed: {avg_time*(i+1):4.3f} seconds || \t " + \
f"||Remaining time: {(avg_time*(n-(i+1))): 4.3f} seconds."
)
return
N = 325
t0 = time.time()
for k in range(N):
# stuff goes here #
time.sleep(0.0001)
# stuff goes here #
simple_progress_bar(k, N, t0)
pip install progressbar2
import os
import time
import progressbar
os.environ['PYCHARM_HOSTED'] = '1' # https://github.com/WoLpH/python-progressbar/issues/237
class COLOR: # https://stackoverflow.com/a/287944/11465149
YELLOW = '\033[93m'
GREEN = '\033[92m'
RED = '\033[91m'
BOLD = '\033[1m'
ENDC = '\033[0m'
widgets=[
'FILE.JSON ',
COLOR.YELLOW , progressbar.Percentage() , COLOR.ENDC,
COLOR.RED + COLOR.BOLD, progressbar.Bar(left=' ', marker='━', right=' '), COLOR.ENDC,
COLOR.YELLOW , progressbar.Timer() , COLOR.ENDC
]
for i in progressbar.progressbar(range(100), widgets=widgets):
time.sleep(0.01)
if i == 99:
widgets[4] = COLOR.GREEN
使用enumerate(...progressbar(max_value=...)
+ this如果您想将其用作下载进度条
您可以使用丰富的库,它具有非常好的终端样式,包括进度条。 首先运行以下命令: pip install rich
来自文档的示例:
import time
from rich.progress import track
for i in track(range(20), description="Processing..."):
time.sleep(1) # Simulate work being done
这是一个非常简单的版本,以防您有一个循环并且只想了解迭代的进展情况,例如每 5000 次迭代的一个点。
my_list = range(0,100000)
counter = 0
for x in my_list:
#your code here
counter = counter + 1
if counter % 5000 == 0:
print(".", end="") # end="" avoids a newline, keeps dots together
print() #this makes sure whatever you print next is in a new line
my_list 不是该计划的一部分。 使用您自己的可迭代对象,无论您在循环什么。 此版本不会提前告诉您总迭代次数。
想拥有最小最少的线条,
for i in range(1,10):
print("Progress: "+i*"#" , end="\r")
time.sleep(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.