Python 进度条
- 2024-12-11 08:48:00
- admin 原创
- 166
问题描述:
当我的脚本正在执行一些可能需要时间的任务时,如何使用进度条?
例如,一个函数需要一些时间才能完成,True
完成后返回。如何在函数执行期间显示进度条?
请注意,我需要实时实现这一点,所以我不知道该怎么做。我需要一个thread
吗?我不知道。
目前,在执行函数时我没有打印任何内容,但如果有进度条就更好了。另外,我更感兴趣的是如何从代码的角度做到这一点。
解决方案 1:
使用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
。
您甚至可以在断开与 jupyter notebook 的连接后使用tqdm.contrib.telegram
或将进度发送到您的手机tqdm.contrib.discord
。
解决方案 2:
使用alive-progress,有史以来最酷的进度条!只需pip install alive-progress
这样,您就可以开始了!
要有效使用任何进度条,即获得完成百分比和预计到达时间,您需要能够告诉它项目总数。然后alive-progress
它将跟踪您当前的处理情况以及需要多长时间!
如果您无法估计总数,请不要担心,alive-progress
它仍然可以工作。
要使用它,您可以直接驾驶alive-progress
'杆:
def compute():
with alive_bar(1000) as bar: # your expected total
for item in items: # the original loop
print(item) # your actual processing here
bar() # call `bar()` at the end
compute()
或者,如果您希望保持代码隔离,只需yield
在处理代码中插入一个(以标记项目何时已被处理),然后alive-progress
像这样驱动'栏:
def compute():
for item in items:
print(item)
yield # simply insert this :)
with alive_bar(1000) as bar:
for i in compute():
bar()
无论哪种方式,您都会获得一个很棒的动画进度条!
|█████████████▎ | ▅▃▁ 321/1000 [32%] in 8s (40.1/s, eta: 16s)
而且它开箱即用,支持很多高级选项!
披露:我是 的骄傲作者alive-progress
,它在 github 上有 5K+⭐️!
阅读https://github.com/rsalmei/alive-progress
上的文档以了解所有高级功能。
看看它在旋转器和栏小部件中可以做的更多动画:
它也适用于 Jupyter Notebooks!
您甚至可以设计自己的动画!
解决方案 3:
有专门的库(比如这个),但也许一些非常简单的东西就可以做到:
import time
import sys
toolbar_width = 40
# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("" * (toolbar_width+1)) # return to start of line, after '['
for i in range(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("]
") # this ends the progress bar
注意:progressbar2是progressbar的一个分支,已经多年没有维护了。
解决方案 4:
无需外部包。一段现成的代码。
您可以自定义进度条符号"#"
,栏目size
,文字prefix
等等。
Python 3.6+(f 字符串)带有剩余时间估算
import sys
import time
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.6+
count = len(it)
start = time.time() # time estimate start
def show(j):
x = int(size*j/count)
# time estimate calculation and string
remaining = ((time.time() - start) / j) * (count - j)
mins, sec = divmod(remaining, 60) # limited to minutes
time_str = f"{int(mins):02}:{sec:03.1f}"
print(f"{prefix}[{u'█'*x}{('.'*(size-x))}] {j}/{count} Est wait {time_str}", end='
', file=out, flush=True)
show(0.1) # avoid div/0
for i, item in enumerate(it):
yield item
show(i+1)
print("
", flush=True, file=out)
[████████████████████████████.........................] 24/50 Est wait 00:05.3
用法:
import time
for i in progressbar(range(15), "Computing: ", 40):
time.sleep(0.1) # any code you need
不需要第二个线程。上面的一些解决方案/包需要。
适用于任何可迭代对象,即
len()
可以用于任何事物。例如list
,任何事物的 adict
`['a', 'b', 'c' ... 'g']`使用生成器只需用 list() 包装它即可。例如
for i in progressbar(list(your_generator), "Computing: ", 40):
,除非工作是在生成器中完成的。在这种情况下,您需要另一种解决方案(如 tqdm)。
您还可以通过更改out
为来更改输出sys.stderr
。
Python 3.3+
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='
', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("
", flush=True, file=out)
Python 2(旧代码)
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
" % (prefix, u"#"*x, "."*(size-x), j, count))
out.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
out.write("
")
out.flush()
解决方案 5:
上述建议非常好,但我认为大多数人只是想要一个现成的解决方案,不依赖外部包,但也可以重复使用。
我收集了上述所有要点,并将其制作成一个函数,并附带一个测试用例。
要使用它,只需复制“def update_progress(progress)”下的行,而不是测试脚本。不要忘记导入系统。每当您需要显示或更新进度条时,请调用此方法。
这是通过直接将“\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
"
if progress < 0:
progress = 0
status = "Halt...
"
if progress >= 1:
progress = 1
status = "Done...
"
block = int(round(barLength*progress))
text = "
Percent: [{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
解决方案 6:
尝试从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
解决方案 7:
对于类似的应用程序(循环跟踪进度),我仅使用了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
解决方案 8:
我喜欢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, "
"
block = int(round(barLength * progress))
text = "
[{}] {:.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%
解决方案 9:
在搜索了等效解决方案后,我刚刚根据自己的需求创建了一个简单的进度类。我想我可以发布它。
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('
' + 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
解决方案 10:
您可以使用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 ]
您可以根据自己的喜好进行更改和自定义。
解决方案 11:
我真的很喜欢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()])
解决方案 12:
一个简单的单行代码:
K = 628318
for k in range(K):
# your stuff
print(end="
|%-80s|" % ("="*(80*(k+1)//K)))
|===================================================================== |
80 是杆的长度。最终你想要一个最终的print()
。
也可以将其放入便利函数中。与 一起yield
,可以模拟 的行为tqdm
:
def progbar(iterobj):
K = len(iterobj)
for k, obj in enumerate(iterobj):
print(end="
|%-80s|" % ("="*(80*(k+1)//K)))
yield obj
print()
raise StopIteration
for k in progbar(range(628318)):
# your stuff
pass
不要忘记数字进度指示器:
K = 628318
for k in range(K):
# your stuff
print(end=f"
{(k+1)/K*100:6.2f} %")
94.53 %
如果需要的话,将两者结合起来并不困难。
关键是“回车”`和抑制默认
end="
"值
print`。
解决方案 13:
使用这个库:fish
(GitHub)。
用法:
>>> import fish
>>> while churning:
... churn_churn()
... fish.animate()
玩得开心!
解决方案 14:
如果这是一个大循环,迭代次数固定,耗时很长,您可以使用我制作的这个函数。每次循环迭代都会增加进度。其中 count 是循环的当前迭代次数,total 是您要循环到的值,size(int) 是您希望条形图的大小,以 10 为增量,即(size 1 =10 个字符,size 2 =20 个字符)
import sys
def loadingBar(count,total,size):
percent = float(count)/float(total)*100
sys.stdout.write("
" + 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 [========== ]
解决方案 15:
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 = '[93m'
GREEN = '[92m'
RED = '[91m'
BOLD = '[1m'
ENDC = '[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=...)
+
解决方案 16:
在 jupyter 笔记本中运行时,使用普通 tqdm 不起作用,因为它会在多行上写入输出。请改用此方法:
import time
from tqdm.notebook import tqdm
for i in tqdm(range(100)):
time.sleep(0.5)
解决方案 17:
您也可以使用illuminate。主要优点是您可以同时记录而不会覆盖进度条。
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()
解决方案 18:
下面的代码是一个非常通用的解决方案,并且还具有已用时间和剩余时间估计。您可以使用任何可迭代对象。进度条的大小固定为 25 个字符,但它可以使用全、半和四分之一块字符以 1% 的步长显示更新。输出如下所示:
18% |████▌ | [0:00:01, 0:00:06]
代码示例:
import sys, time
from numpy import linspace
def ProgressBar(iterObj):
def SecToStr(sec):
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
return u'%d:%02d:%02d'%(h, m, s)
L = len(iterObj)
steps = {int(x):y for x,y in zip(linspace(0, L, min(100,L), endpoint=False),
linspace(0, 100, min(100,L), endpoint=False))}
qSteps = ['', u'/u258E', u'/u258C', u'/u258A'] # quarter and half block chars
startT = time.time()
timeStr = ' [0:00:00, -:--:--]'
activity = [' -',' \\',' |',' /']
for nn,item in enumerate(iterObj):
if nn in steps:
done = u'/u2588'*int(steps[nn]/4.0)+qSteps[int(steps[nn]%4)]
todo = ' '*(25-len(done))
barStr = u'%4d%% |%s%s|'%(steps[nn], done, todo)
if nn>0:
endT = time.time()
timeStr = ' [%s, %s]'%(SecToStr(endT-startT),
SecToStr((endT-startT)*(L/float(nn)-1)))
sys.stdout.write('
'+barStr+activity[nn%4]+timeStr); sys.stdout.flush()
yield item
barStr = u'%4d%% |%s|'%(100, u'/u2588'*25)
timeStr = ' [%s, 0:00:00]
'%(SecToStr(time.time()-startT))
sys.stdout.write('
'+barStr+timeStr); sys.stdout.flush()
# Example
s = ''
for c in ProgressBar(list('Disassemble and reassemble this string')):
time.sleep(0.2)
s += c
print(s)
欢迎提出改进建议或其他评论。干杯!
解决方案 19:
在 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='
')
bar_length = 30
total = 100
for i in range(0, total + 1):
show_progress_bar(bar_length, i, total)
time.sleep(0.1)
print('
')
解决方案 20:
2022 无需外部库的简单进度条答案
import time, sys
def progress(size):
for item in range(size):
if(item==0):
print("[",end="")
elif(item==size-1):
print("]",end="
")
else:
#main work goes here
time.sleep(0.1)
print("%",end="")
sys.stdout.flush()
progress(50)
解决方案 21:
我喜欢这个页面。
从简单示例开始,然后转到多线程版本。开箱即用。无需第三方软件包。
代码看起来会像这样:
import time
import sys
def do_task():
time.sleep(1)
def example_1(n):
for i in range(n):
do_task()
print '.',
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('/')
elif (i%4) == 1:
sys.stdout.write('-')
elif (i%4) == 2:
sys.stdout.write('\\')
elif (i%4) == 3:
sys.stdout.write('|')
sys.stdout.flush()
time.sleep(0.2)
i+=1
if kill == True:
print ' ABORT!',
else:
print ' 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
解决方案 22:
我使用format()
方法制作了一个加载条。这是我的解决方案:
import time
loadbarwidth = 23
for i in range(1, loadbarwidth + 1):
time.sleep(0.1)
strbarwidth = '[{}{}] - {}
'.format(
(i * '#'),
((loadbarwidth - i) * '-'),
(('{:0.2f}'.format(((i) * (100/loadbarwidth))) + '%'))
)
print(strbarwidth ,end = '')
print()
输出:
[#######################] - 100.00%
解决方案 23:
使用进度库!
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()
解决方案 24:
这是一个简短的解决方案,可以通过编程来构建加载栏(您必须决定需要多长时间)。
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('
%s Loading at %3d percent!' % (loading, i*100/n), end='')
loading = loading[:i] + '#' + loading[i+1:]
time.sleep(load)
if i==n: print()
解决方案 25:
如果您的工作无法分解为可测量的部分,您可以在新线程中调用您的函数并计时它需要多长时间:
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 "
Work Done"
您显然可以根据需要提高计时精度。
解决方案 26:
我喜欢Gabriel 的回答,但我把它改得更灵活。你可以将进度条长度发送给函数,并获取你想要的任意长度的进度条。并且你不能让进度条的长度为零或负数。此外,你可以像Gabriel 的回答那样使用这个函数(参见示例 #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 = "
" # 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.
")
# Example #1:
print('Example #1')
Runs = 10
for i in range(Runs + 1):
progressBar = "
Progress: " + ProgressBar(10, i, Runs)
ShowBar(progressBar)
time.sleep(1)
# Example #2:
print('
Example #2')
Runs = 10
for i in range(Runs + 1):
progressBar = "
Progress: " + ProgressBar(10, i, 20, '|', '.')
ShowBar(progressBar)
time.sleep(1)
print('
Done.')
# Example #2:
Runs = 10
for i in range(Runs + 1):
ProgressBar(10, i)
time.sleep(1)
结果:
这是一个简单的进度条。
示例 #1
进度:[###-------] 30%
示例 #2
进度:[|||||||||||||........] 60%
完毕。
解决方案 27:
我想我有点晚了,但是对于使用当前版本的 python 3 的人来说,这应该有效,因为它使用了 “f 字符串”,如 Python 3.6 PEP 498中引入的那样:
代码
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='
')
例子
#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%
解决方案 28:
这是我的简单解决方案:
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="
")
# USAGE:
for i in range(0,101):
time.sleep(0.1)
progress(i,100)
print("..."*5, end="
")
print("Done")
解决方案 29:
一个非常简单的方法:
def progbar(count: int) -> None:
for i in range(count):
print(f"[{i*'#'}{(count-1-i)*' '}] - {i+1}/{count}", end="
")
yield i
print('
')
用法:
from time import sleep
for i in progbar(10):
sleep(0.2) #whatever task you need to do
解决方案 30:
已经有很多令人惊叹的答案,但我仍然想分享我对进度条的解决方案。
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"
|{bar}| {(100/width)*percent:.2f}%", end="
")
numbers = range(0, 1000)
numbersLen = len(numbers)
for i in numbers:
sleep(0.01) # Do something usefull here
progress_bar(i, numbersLen)
编辑:
如果您正在寻找一个可以根据终端宽度调整其宽度的栏,并在末尾显示消息,那么这个也是可行的。请注意,如果终端太窄,消息就会消失,因为如果栏太宽而无法显示一行,栏就会断开。
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"
|{bar}| {(100/width)*percent:.2f}% " + message, end="
")
扫码咨询,免费领取项目管理大礼包!