Python进度B

2024-03-29 13:16:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

注意,我需要这个是实时的,所以我不知道该怎么办。我需要一个thread吗?我不知道。

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


Tags: 函数代码进度条脚本true时间thread感兴趣
2条回答

使用tqdm可以在一秒钟内将进度表添加到循环中:

In [1]: import time

In [2]: from tqdm import tqdm

In [3]: for i in tqdm(range(10)):
   ....:     time.sleep(3)

 60%|██████    | 6/10 [00:18<00:12,  0.33 it/s]

此外,还有一个图形版的tqdm,因为^{}^{}):

In [1]: import time

In [2]: from tqdm import tqdm_gui

In [3]: for i in tqdm_gui(range(100)):
  ....:     time.sleep(3)

tqdm gui window

但是要小心,因为tqdm_gui可以引发一个TqdmExperimentalWarning: GUI is experimental/alpha,您可以通过使用warnings.simplefilter("ignore")忽略它,但它将忽略之后代码中的所有警告。

有一些特定的库(like this one here),但也许一些非常简单的方法可以做到:

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的叉子,多年来没有保养过。

相关问题 更多 >