Python 中有多种方式可以实现进度条,下面介绍几种常见的方法:

实例

import time
for i in range(101): # 添加进度条图形和百分比
    bar = '[' + '=' * (i // 2) + ' ' * (50 - i // 2) + ']'
    print(f"\r{bar} {i:3}%", end='', flush=True)
    time.sleep(0.05)
print()

实例

import sys
import time

def progress_bar(current, total, bar_length=50):
    percent = float(current) / total
    arrow = '=' * int(round(percent * bar_length) - 1) + '>'
    spaces = ' ' * (bar_length - len(arrow))
   
    sys.stdout.write(f"\r进度: [{arrow + spaces}] {int(round(percent * 100))}%")
    sys.stdout.flush()

for i in range(101):
    time.sleep(0.1)
    progress_bar(i, 100)
print()  # 换行

使用不同颜色变化进度:

实例

import time
import sys

def progress_bar(current, total, bar_length=50):
    """
    显示进度条
    :param current: 当前进度
    :param total: 总进度
    :param bar_length: 进度条长度
    """

    percent = current / total
    arrow = '=' * int(round(percent * bar_length) - 1) + '>'
    spaces = ' ' * (bar_length - len(arrow))
   
    # 添加颜色(可选)
    color_code = 32  # 绿色
    if percent > 0.7:
        color_code = 33  # 黄色
    if percent > 0.9:
        color_code = 31  # 红色
   
    # 格式化输出
    sys.stdout.write(f"\r\033[{color_code}m进度: [{arrow + spaces}] {current:3d}/{total} ({percent:.0%})\033[0m")
    sys.stdout.flush()

# 使用示例
total = 100
for i in range(total + 1):
    progress_bar(i, total)
    time.sleep(0.05)

print("\n完成!")  # 完成后换行

使用标准库 tqdm

tqdm 是最流行的进度条库之一,安装简单,使用方便。

pip 安装标准库:

pip install tqdm

实例

from tqdm import tqdm
import time

# 基本用法
for i in tqdm(range(100)):
    time.sleep(0.1)  # 模拟任务

# 带描述的进度条
with tqdm(range(100), desc="处理进度") as pbar:
    for i in pbar:
        time.sleep(0.1)
       
# 手动更新
pbar = tqdm(total=100)
for i in range(10):
    time.sleep(0.5)
    pbar.update(10)  # 每次更新10
pbar.close()