TQDM多行彩色进度条打印

4
当我使用bar_format选项添加颜色时,我不确定为什么我的TQDM进度条会分成多行。这似乎与迭代次数有关,因为当我只运行10次迭代而不是1389次时,它不会分行(请参见图像)。此外,当我运行相同的代码但不修改进度条颜色时,它可以正常工作。
问题图片: Problem 少一些迭代次数时的图片: Fewer iterations 没有颜色修改时的图片: No color
from tqdm import tqdm
from colorama import Fore

dnames = [...]  # List of directories
cmap = [  # List of colors, same length as `dnames`
    '\x1b[38;5;231m',
    '\x1b[38;5;194m',
    '\x1b[38;5;151m',
    '\x1b[38;5;114m',
    '\x1b[38;5;71m',
    '\x1b[38;5;29m',
    '\x1b[38;5;22m',
    '\x1b[38;5;22m',
    '\x1b[38;5;22m',
    '\x1b[38;5;22m'
    # ...may include many more colors
]

# Initialize progress bar and color variable
pbar = tqdm(dnames, unit='dir')
current_color = None

for i, dname in enumerate(dnames):

    # Update color of pbar if different from last iteration
    if current_color != cmap[i]:
        pbar.bar_format = "{l_bar}%s{bar}%s{r_bar}" % (cmap[i], Fore.RESET)
        current_color = cmap[i]

    # For loop body goes here

    # Update pbar
    pbar.update(1)

pbar.close()
2个回答

8

你的代码对我来说工作得非常好,其他回答提到的 tqdm 版本可能会有所帮助。简而言之,你需要更新。


如果有人想知道如何设置进度条的颜色,可以参考以下步骤:

from tqdm import tqdm
from time import sleep

for i in tqdm(range(100), colour="red"):
    sleep(0.001)

有效的颜色选择:[十六进制(#00ff00),黑色,红色,绿色,黄色,蓝色,洋红,青色,白色]

文档:

https://tqdm.github.io/docs/tqdm/#format_meter


2

已在 tqdm>=4.41.1 版本中修复。

此外,最新版本 tqdm>=4.50.0 增加了一个 colour 参数,使这个过程变得更加容易。


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