酷炫的終端進度條——Python 和 Bash


想像一個你需要時間運行的情況,比如用 Python 開發一個腳本、連接到互聯網、獲取文件、丟棄數據等等。

當我運行腳本時,我不知道腳本是否正在運行,卡住,或者我需要等待多長時間。正確的?

如果您有一個以百分比顯示剩餘時間或剩餘進度的加載屏幕或進度條,這不是問題。您可以使用兩者來創建進度條。本教程將向您展示如何使用 Python 和 Bash 在終端中創建進度條。

先決條件

在本教程中,您將使用 Ubuntu 來運行腳本。 Ubuntu 是一個基於 Linux 的操作系統。 Ubuntu 上已經安裝了 Python 和 bash,因此您無需再次安裝它們。 在基於 Debian 的操作系統上遵循本教程沒有任何問題。

如果您使用的是 Windows 操作系統,則需要從終端運行腳本,因此請確保已安裝 Python 並設置了環境變量。 如果您想在 Windows 上嘗試 bash,則需要 WSL(適用於 Linux 的 Windows 子系統)。

使用 Python 的進度條

Python是一種高端編程語言。你可以用它來實現幾乎任何事情。 Python中有許多很酷的庫用於創建進度條。在本教程中,我們將介紹其中的一些。

  • tqdm
  • 生活進步
  • 你好
  • 阿斯平

1) TQDM

Tqdm 是一個易於使用的庫。這在循環中特別有效。它給出了一個循環時間表。只需兩行代碼即可完成。

安裝

按終端並運行以下命令:

❯ pip3 install tqdm

如何使用

使用 tqdm 就像將它添加到 for 循環一樣簡單,如下所示:

from tqdm import tqdm
import time
for i in tqdm(range(20), desc="tqdm() Progress Bar"):
    time.sleep(0.1)
    # some tasks here
    # some more operations here

這裡 desc 它是用於描述進度條的眾多參數之一。例如,在獲取文件時,它可能是“下載”。

輸出

Tqdm 可以在您的代碼中以不同的方式使用。對於其他的片段和功能,您需要遵循官方文檔。

2) ALIVE_PROGRESS

這是另一個帶有一些很酷的動畫的進度條庫。 Alive_progress 很棒,因為它可以讓您完全控制進度條並獲得動態。它比 tqdm 好很多,因為它有更多的功能,你可以從各種動畫中進行選擇。

安裝

按終端並運行以下命令:

❯ pip install alive-progress

如何使用

如果您有從 Internet 下載文件的腳本,則示例代碼:

from alive_progress import alive_bar
import time

for i in range(3):
    with alive_bar(100, ctrl_c=False, title=f'Downloading {i}') as bar:
         for i in range(100):
             time.sleep(0.02)
             bar()

在哪裡 100 進度的最大長度。 ctrl_c = False 方法 CTRL + C 執行進度條中的代碼時不起作用(CTRL + C用於結束終端中的任務)。如果您有一個關鍵任務正在運行並且您不希望用戶完成該任務,這將特別有用。默認 True..什麼時候 title 進度條的標題。

輸出

您還可以更改進度條的主題,如下所示:

from alive_progress import alive_bar
import time

for i in range(3):
    with alive_bar(100, ctrl_c=False, title=f'Downloading {i}', bar="halloween", spinner="twirls") as bar:
         for i in range(100):
             time.sleep(0.02)
             bar()

還支持微調器。

輸出

您可以從許多可用的主題和微調器中進行選擇。您可以一次查看所有內容,然後選擇最適合您的。

from alive_progress.styles import showtime

showtime()

輸出

有關更多信息,請訪問 github 存儲庫。

3、你好

Halo 更像是一個微調器,而不是加載屏幕。操作時間短時可以使用。

安裝

按終端並運行以下命令:

❯ pip install halo

如何使用

from __future__ import unicode_literals
import os
import sys
import time

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from halo import Halo

success_message="Loading success"
failed_message="Loading failed"
unicorn_message="Loading unicorn"

spinner = Halo(text=success_message, spinner="dots")

try:
    spinner.start()
    time.sleep(1)
    spinner.succeed()
    spinner.start(failed_message)
    time.sleep(1)
    spinner.fail()
    spinner.start(unicorn_message)
    time.sleep(1)
    spinner.stop_and_persist(symbol="🦄".encode('utf-8'), text=unicorn_message)
except (KeyboardInterrupt, SystemExit):
    spinner.stop()

輸出

檢查 github 存儲庫以獲取更多信息。

4)阿斯平

另一個用於命令行應用程序的微調器庫。 Yaspin 有多種選擇。適用於需要比平時更長的操作。

安裝

按終端並運行以下命令:

❯ pip install yaspin

如何使用

import time
from random import randint
from yaspin import yaspin
from yaspin.spinners import Spinners

with yaspin(text="Loading", color="yellow") as spinner:
    time.sleep(1)  # time consuming code

    success = randint(0, 1)
    if success:
        spinner.ok("✅ ")
    else:
        spinner.fail("💥 ")
        
 
with yaspin(Spinners.earth, text="Earth") as sp:
    time.sleep(1)                # time consuming code

    # change spinner
    sp.spinner = Spinners.moon
    sp.text = "Moon"

    time.sleep(1)  
    

    
with yaspin(text="Colors!") as sp:
    # Support all basic termcolor text colors
    colors = ("red", "green", "yellow", "blue", "magenta", "cyan", "white")

    for color in colors:
        sp.color, sp.text = color, color
        time.sleep(0.5)

輸出

請看這個官方網站。

使用 Bash 進度條 重擊

Bash 基本上是基於 GNU 的操作系統的命令語言或命令行解釋器。 你可以在 Linux 操作系統上看到它。 不是Linux。 Linux是內核。 Bash 在基於 GNU 的操作系統上運行。示例:Debian。

創建 Shell 腳本以執行特定任務,例如將大量文件複製到文件夾、克隆 GitHub 存儲庫以及在其中自動安裝所有依賴項……當動作在後台運行時,顯示進度條是錦上添花。

讓我們從創建一個 shell 文件開始。例如: test.sh..我正在使用 gedit 文本編輯器。你可以使用任何你喜歡的東西。

如何使用

複製下面的代碼得到一個簡單的進度條

#!/bin/bash

bar="####################"
echo ""
for i in {1..20}; do
    echo -ne "rDownloading  ${bar:0:$i}" 
    sleep .1                 
done
echo ""
echo ""
echo "This is a simple progress bar"

您可以使用以下終端運行代碼:

❯ bash test.sh

輸出

如果您想在終端中顯示動畫和彩色加載屏幕,這是另一個示例。

#!/垃圾桶/bash

函数 pro { bar="" for (( x=50; x 

OUTPUT

If you want to integrate a progress bar in a GUI-based command-line application the following code may be suitable for you.

#!/bin/bash

seq 1 100|dialog --title "Downloading Files" --gauge "Please wait ..." 11 60 0
sleep 1

輸出

您還可以查看操作描述並對其進行修改以添加適當的標題。

#!/bin/bash

phasess=( 
    'Ready to perform operations...'
    'Performing some operations...'
    'Please wait ...'
    'almost there...'
)   

for i in $(seq 1 100); do  
    sleep 0.04

    if [ $i -eq 100 ]; 然后 echo -e "XXXn100nDone!nXXX" elif [ $(($i % 25)) -eq 0 ]; 然后让 "phase = $i / 25" echo -e "XXXn$in${phasess[phase]}nXXX" else echo $i fi done |whiptail --title '这是一个 GUI 进度条' --gauge "${phasess[0]}" 6 60 0

輸出

包起來! 搖動表情符號 3d

這使您的命令行應用程序更加用戶友好和靈活。我們希望您發現本教程很有用。

推薦文章

  • 用這個簡單的技巧為提示著色
  • 輕鬆更改終端默認外殼
  • 使用 Source 在 Debian / Ubuntu 上安裝最新的 Python