Python 进度条

安装 Python 库

pip install rich

代码实现示例

普通进度条

from rich.progress import track
import time

for i in track(range(100), description="正在载入..."):
    time.sleep(0.1)

普通进度条

下载进度条

from rich.progress import track
import requests
from os import path

URL = "https://cakkl.com/resource/windows/ntuser.dat"  # 下载地址

# 检查 URL对应的 / 网站 是否有效 如 https://cakkl.site 有效
response = requests.get(URL.split("/")[0] + "//" + URL.split("/")[2])
if response.status_code != 200:
    print("URL 无效")
    exit()

# dir_name 为 当前目录下 保存为 URL 截取的文件名
dir_name = path.join(path.dirname(__file__), URL.split("/")[-1])  # 保存路径
response = requests.get(URL, stream=True)
total_size_in_bytes = int(response.headers.get("content-length", 0))
block_size = 1024
total = total_size_in_bytes // block_size

with open(f"{dir_name}", "wb") as f:
    for chunk in track(
        response.iter_content(chunk_size=block_size),
        total=total,
        description="正在下载...",
    ):
        f.write(chunk)

下载进度条

多进度条

import time
from rich.progress import Progress

with Progress() as progress:
    task1 = progress.add_task("[red]Downloading...", total=100)
    task2 = progress.add_task("[green]Processing...", total=100)
    task3 = progress.add_task("[cyan]Cooking...", total=100)

    while not progress.finished:
        progress.update(task1, advance=0.5)
        progress.update(task2, advance=0.3)
        progress.update(task3, advance=0.9)
        time.sleep(0.02)

多进度条

自定义进度条

import time
from rich.panel import Panel
from rich.progress import Progress

class FrameProgress(Progress):
    def get_renderables(self):
        yield Panel(
            self.make_tasks_table(self.tasks), expand=False
        )  # expand=False 使得进度条不会占满整个屏幕

with FrameProgress() as progress:
    task1 = progress.add_task("[red]Master Progress Bar...", total=10)
    for i in range(5):
        task2 = progress.add_task(f"[green]Sub Progress Bar: {i + 1}...", total=10)
        for j in range(10):
            progress.update(task2, advance=1)
            time.sleep(1)
        time.sleep(1)
        progress.update(task1, completed=1)

自定义进度条