使用 tqdm 的 python 进度条不停留在一行上

问题描述 投票:0回答:3

我正在尝试运行一个脚本,尝试通过 puppet 管理在 centos7 系统上安装模块。 我想为运行脚本时发生的安装实现一个进度条。 我正在使用 tqdm 模块来执行此操作。 这是我如何实现该模块的快照:

from tqdm import tqdm
for i in tqdm(commands):
    res = run_apply(i)

这里 run_apply() 是实际处理运行和应用 puppet 配置的函数。

到目前为止一切顺利,我得到了一个进度条,但当执行消息写入控制台时,它会不断向下移动控制台。 但是,我需要进度条在控制台底部保持不变并动态更新,而不需要运行消息干扰进度条。 我希望控制台上的执行相关消息能够按照需要继续显示,但进度条应该从执行开始到结束都停留在底部。

以下是我所看到的:

        File line: 0.00
          Package: 0.05
          Service: 0.19
             File: 0.23
             Exec: 0.23
         Last run: 1470308227
   Config retrieval: 3.90
            Total: 4.60
Version:
           Config: 1470308220
           Puppet: 3.7.3
now here x
result:  2
 38%|█████████████████████████████████████▋                                                            | 5/13 [00:29<00:51,  6.44s/it]about to:  profiles::install::download_packages
about to run puppet apply --summarize  --detailed-exitcodes --certname puppet -e "include profiles::install::download_packages"
Error: Could not find class profiles::install::download_packages for puppet on node puppet
Error: Could not find class profiles::install::download_packages for puppet on node puppet
now here x
result:  1
 46%|█████████████████████████████████████████████▏                                                    | 6/13 [00:32<00:36,  5.27s/it]about to:  profiles::install::install
about to run puppet apply --summarize  --detailed-exitcodes --certname puppet -e "include profiles::install::install"
Error: Could not find class profiles::install::install for puppet on node puppet
Error: Could not find class profiles::install::install for puppet on node puppet
now here x
result:  1
 54%|████████████████████████████████████████████████████▊                                             | 7/13 [00:34<00:26,  4.45s/it]about to:  stx_network
about to run puppet apply --summarize  --detailed-exitcodes --certname puppet -e "include stx_network"
Notice: Compiled catalog for puppet in environment production in 0.84 seconds
Notice: /Stage[main]/Stx_network/Tidy[purge unused nics]: Tidying File[/etc/sysconfig/network-scripts/ifcfg-lo]
...  

请让我知道如何实现我想要的。

python progress-bar tqdm
3个回答
39
投票

对于要在进度条上方打印的消息,您需要向 tqdm 发出信号,表明您正在打印消息(否则 tqdm 或任何其他进度条都无法知道您正在进度条旁边输出消息)。

为此,您可以使用

tqdm.write(msg)
而不是
print(msg)
来打印消息。如果您不想修改
run_apply()
以使用
tqdm.write(msg)
而不是
print(msg)
,您可以 从顶级脚本通过 tqdm 重定向所有标准输出,如下所述


0
投票

我发现了这个很棒的图书馆:Rich

无需摆弄

print
或用
tqdm.write()
替换它们。只需添加
from rich.progress import track
并使用
track()
代替
tqdm()
即可。

太方便了!


-7
投票

尝试使用: 进度条

import Progressbar
progress = progressbar.ProgressBar()
for i in progress(range(30)):
    time.sleep(0.1)

它看起来像这样: 43% (30 中的 13) |############################ |经过时间:0:00:01 预计到达时间:0:00:01

© www.soinside.com 2019 - 2024. All rights reserved.