Python 进度条 [英] Python Progress Bar

查看:71
本文介绍了Python 进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I use a progress bar when my script is doing some task that is likely to take time?

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

For example, a function which takes some time to complete and returns True when done. How can I display a progress bar during the time the function is being executed?

请注意,我需要这是实时的,所以我不知道该怎么做.为此我需要一个 thread 吗?我不知道.

Note that I need this to be in real time, so I can't figure out what to do about it. Do I need a thread for this? I have no idea.

现在我在执行函数时没有打印任何内容,但是进度条会很好.此外,我对如何从代码的角度完成这项工作更感兴趣.

Right now I am not printing anything while the function is being executed, however a progress bar would be nice. Also I am more interested in how this can be done from a code point of view.

推荐答案

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

There are specific libraries (like this one here) but maybe something very simple would do:

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

注意:progressbar2progressbar 多年未维护.

Note: progressbar2 is a fork of progressbar which hasn't been maintained in years.

这篇关于Python 进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆