当我的脚本正在执行一些可能需要时间的任务时,我如何使用进度条?
例如,一个函数需要一段时间才能完成,完成后返回True。如何在函数执行期间显示进度条?
请注意,我需要这是实时的,所以我不知道该怎么做。我需要一根线吗?我不知道。
现在我没有打印任何东西,而函数正在执行,但一个进度条会很好。此外,我更感兴趣的是从代码的角度如何做到这一点。
当我的脚本正在执行一些可能需要时间的任务时,我如何使用进度条?
例如,一个函数需要一段时间才能完成,完成后返回True。如何在函数执行期间显示进度条?
请注意,我需要这是实时的,所以我不知道该怎么做。我需要一根线吗?我不知道。
现在我没有打印任何东西,而函数正在执行,但一个进度条会很好。此外,我更感兴趣的是从代码的角度如何做到这一点。
当前回答
PIP安装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,以防你想使用它作为下载进度条
其他回答
iterrows的Progressbar。调整了@eusoubrasileiro代码,用于在循环遍历数据帧的行时显示进度。此外还显示百分比、ith/count、经过秒数、eps /sec、剩余秒数。允许指定第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
使用进度库!
pip install progress
下面是我编写的一个自定义子类,用于将ETA/流逝时间格式化为更好读的格式:
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
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 range(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是progressbar的一个分支,已经很多年没有维护过了。
我喜欢加布里埃尔的答案,但我改变了它的灵活性。您可以将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% 完成了。
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
输出