Python tqdm包 - 如何配置以减少状态栏更新频率

17
我正在使用Python 3.6 (Anaconda 3, Windows 10 x64, PyCharm IDE)中的tqdm包(v4.19.5)来循环200K+次。它会在控制台中频繁打印状态栏,以至于之前的历史记录消失了。请问有没有办法限制状态栏更新的频率?我在网上和tqdm网站上都找不到解决方案。当前,我的状态栏是这样打印的。理想情况下,我希望设置一个百分比变化的上限。例如,每1%变化/进度更新一次。

enter image description here

5个回答

21

11

被接受的答案和引用的公共API

tqdm.tqdm(iterable, miniters=int(223265/100))

代码正确,但代码位置已更改至此处:https://github.com/tqdm/tqdm/blob/master/tqdm/std.py#L890-L897

下面是miniters选项的说明:

miniters  : int or float, optional
    Minimum progress display update interval, in iterations.
    If 0 and `dynamic_miniters`, will automatically adjust to equal
    `mininterval` (more CPU efficient, good for tight loops).
    If > 0, will skip display of specified number of iterations.
    Tweak this and `mininterval` to get very efficient loops.
    If your progress is erratic with both fast and slow iterations
    (network, skipping items, etc) you should set miniters=1.

9

使用mininterval选项非常方便,它定义了更新之间的最小时间间隔。例如,要每n_seconds更新一次,请使用:

tqdm(iterable, mininterval=n_seconds)

0

我可能看到的问题与你所询问的问题不同:你的进度条更新每次都会写入独立的新行,这是Pycharm多年来存在的一个错误。如果你直接在命令行中运行Python脚本,应该只会显示一行进度,并且会持续更新。或者,你可以在运行/调试配置中设置“在输出控制台中模拟终端”(请参见附图)。然而,这个问题可能已经通过后续的更新修复。

编辑:另外,tqdm.tqdm(iterable, position=0)也可能有所帮助。

Screenshot of Pycharm Run configuration


0

简短回答,使用miniters或者(minintervalmaxinterval)是可行的方法。

详细回答:

  • 使用 minintervalmaxinterval (默认分别为0.1秒和10秒)
  • 或者使用 minitersmaxinterval=float("inf")(在tqdm<=4.64.1中请参阅#1429
  • 并在调用 set_postfixset_postfix_str 时将 refresh=False

三个例子:

from tqdm import tqdm
from time import sleep

N = 100000

# mininterval and maxinterval in seconds
for i in tqdm(range(N), total=N, mininterval=2, maxinterval=2):
    sleep(0.3)

# miniters and maxinterval=float("inf")
for i in tqdm(range(N), total=N, miniters=50, maxinterval=float("inf")):
    sleep(0.3)

# use refresh=False in set_postfix
progress_bar = tqdm(range(N), total=N, miniters=240, maxinterval=float("inf"))
for i in progress_bar:
    sleep(0.3)
    progress_bar.set_postfix({"i": i}, refresh=False)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接