当我的脚本正在执行一些可能需要时间的任务时,我如何使用进度条?
例如,一个函数需要一段时间才能完成,完成后返回True。如何在函数执行期间显示进度条?
请注意,我需要这是实时的,所以我不知道该怎么做。我需要一根线吗?我不知道。
现在我没有打印任何东西,而函数正在执行,但一个进度条会很好。此外,我更感兴趣的是从代码的角度如何做到这一点。
当我的脚本正在执行一些可能需要时间的任务时,我如何使用进度条?
例如,一个函数需要一段时间才能完成,完成后返回True。如何在函数执行期间显示进度条?
请注意,我需要这是实时的,所以我不知道该怎么做。我需要一根线吗?我不知道。
现在我没有打印任何东西,而函数正在执行,但一个进度条会很好。此外,我更感兴趣的是从代码的角度如何做到这一点。
当前回答
这个进度条显示了每完成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%]
>>>
其他回答
已经有很多好的答案,但添加这个特定的基于@HandyGold75的答案,我希望它在特定的上下文中是callabe,有一个初始的msg,加上在结束时的几秒钟的时间反馈。
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)
使用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。笔记本电脑工作在两个终端和笔记本电脑。
tqdm。Contrib包含一些辅助函数,用于执行枚举、映射和压缩等操作。在tqdm.contrib.concurrent中有并发映射。
你甚至可以使用tqdm.contrib.telegram或tqdm.contrib.discord从jupyter笔记本断开连接后将进度发送到你的手机。
我真的很喜欢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()])
已经有很多令人惊叹的答案,但我想分享我对进度条的解决方案。
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)
编辑:
如果你正在寻找一个条,调整它是基于终端的宽度和可能的消息在结束,然后这也是工作。请注意,如果终端太窄,消息将消失,因为如果它太宽,竖条将断开。
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")
您应该将进度条链接到手头的任务(以便它度量进度:D)。例如,如果您正在对一个文件进行ftp传输,您可以告诉ftplib获取一个特定大小的缓冲区,比如128K,然后您将128K所代表的文件大小的百分比添加到进度条中。如果您正在使用CLI,并且进度表有20个字符长,那么当文件传输了1/20时,您将添加一个字符。