当我的脚本执行一些可能需要时间的任务时,如何使用进度条呢?
例如,在完成某个函数并返回True
时需要一定的时间。我如何在函数执行期间显示进度条呢?
请注意,我需要实时显示进度条,所以我不知道该怎么办。我需要为此使用thread
吗?我不知道。
目前我在函数执行期间没有任何打印输出,但一个进度条会很好。我更关心的是从代码角度如何实现这一点。
当我的脚本执行一些可能需要时间的任务时,如何使用进度条呢?
例如,在完成某个函数并返回True
时需要一定的时间。我如何在函数执行期间显示进度条呢?
请注意,我需要实时显示进度条,所以我不知道该怎么办。我需要为此使用thread
吗?我不知道。
目前我在函数执行期间没有任何打印输出,但一个进度条会很好。我更关心的是从代码角度如何实现这一点。
使用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 的描述中阅读更多内容
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')
注意:如果需要,您可以修改填充和“void”字符。
这个进度条显示每完成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%]
>>>
这是创建进度条的简单方法
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)
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
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不是计划的一部分。使用您自己的可迭代对象,无论您正在循环遍历什么。 这个版本不会提前告诉您总共有多少次迭代。
with open(path2file, 'wb+') as f: # with open(path2file, 'w+') as f: f.write(data.read())
- Charlie Parker