在脚本中使用Python进度条

2 投票
2 回答
1974 浏览
提问于 2025-04-17 02:34

我想在我的脚本中显示一个进度条,因为处理大文件时执行需要花费很多时间。我查看了python进度条模块

还有一些示例,使用起来很好也很有趣,但根据示例,所有的值都是预先定义好的。因为我们无法预测程序或函数的最大执行时间,所以我不知道该如何在我的脚本中使用进度条函数。

for data in files:
     crawl_data(data)

这是一个耗时的crawl_data函数,我该如何设置进度条的值呢?

pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=300).start()
for i in range(300):
    time.sleep(0.01)
    pbar.update(i+1)
pbar.finish()

我该如何在上面的代码中定义这个范围和最大值?

2 个回答

0

如果你无法预测程序执行的时间,那么进度条就没什么用处了(还记得以前的微软进度条吗?)。你可能更需要的是一种活动指示器。从网络2.0开始,通常会使用一些旋转的图标来表示正在进行的操作。

3

这是我成功实现的内容。

标准输出

Working: | Elapsed Time: 0:00:10  

Python代码

import time
import progressbar
import threading

def crawl_data(data):
    # sleep for 10 seconds
    time.sleep(10)
# end of def crawl_data

def main():
    data = 'some data'
    widgets = ['Working: ', progressbar.AnimatedMarker(), ' ',
                   progressbar.Timer()]
    pbar = progressbar.ProgressBar(widgets=widgets)
    # creating thread to run crawl_data()
    thread = threading.Thread(target=crawl_data,
                              args=(data,))
    thread.daemon = True
    # starting thread and progress bar
    thread.start()
    pbar.start()
    i = 1
    # continuous loop until crawl_data thread is not alive
    while True:
        # update every second
        time.sleep(1)
        pbar.update(i)
        if not thread.is_alive():
            pbar.finish()
            break
        # end of if thread is not alive
        i += 1
    # end of continuous loop until crawl_data thread is not alive
    # prints a new line
    print
# end of def main

# run main
main()

撰写回答