Python 进度条

新手上路,请多包涵

当我的脚本正在执行一些可能需要时间的任务时,如何使用进度条?

例如,一个需要一些时间才能完成并在完成后返回 True 的函数。如何在函数执行期间显示进度条?

请注意,我需要它是实时的,所以我不知道该怎么做。我需要 thread 吗?我不知道。

现在我在执行函数时没有打印任何东西,但是进度条会很好。此外,我更感兴趣的是如何从代码的角度来做到这一点。

原文由 user225312 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 502
2 个回答

有特定的库( 比如这里 的这个),但也许可以做一些非常简单的事情:

 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 是一个多年未维护的 进度 条的分支。

原文由 ChristopheD 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 tqdmconda install tqdmpip 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 contains some helper functions to do things like enumerate , map , and zip . tqdm.contrib.concurrent 中有并发映射。

使用 tqdm.contrib.telegramtqdm.contrib.discord 从 jupyter notebook 断开连接后,您甚至可以将进度发送到手机。

GIF 显示使用 tqdm.contrib.telegram 在 Telegram 移动应用程序中显示进度条的输出示例

原文由 scls 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题