[英]python progress bar using tqdm not staying on a single line
我正在嘗試運行一個腳本,試圖通過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]
...
請讓我知道如何實現我想要的。
對於要在進度條上方打印的消息,您需要向tqdm發信號通知您正在打印消息(否則tqdm,也沒有任何其他進度條,無法知道您在進度條旁邊輸出消息)。
為此,您可以使用tqdm.write(msg)
而不是print(msg)
。 如果您不想修改run_apply()
以使用tqdm.write(msg)
而不是print(msg)
,則可以通過tqdm從頂級腳本重定向所有標准輸出,如此處所述 。
嘗試使用:Progressbar
import Progressbar
progress = progressbar.ProgressBar()
for i in progress(range(30)):
time.sleep(0.1)
看起來像這樣:43%(13/30)| ############################ 經過時間:0:00:01 ETA:0:00:01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.