Python 进度条
发表于更新于
字数总计:15k 鞍山
PythonPython 进度条
魔力刘易斯安装 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"
response = requests.get(URL.split("/")[0] + "//" + URL.split("/")[2])
if response.status_code != 200:
print("URL 无效")
exit()
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
)
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)