炫酷进度条

进度条(英语:Progress bar)是一种图形控制元素,是用于扩展视觉化计算机操作,展示任务的处理进度,例如下载、文件传输或安装的进度。 有时,图形以百分比格式伴随进度的文本表示。 该概念也可被视为在媒体播放器中的“时间条”英文:playback bars,用于查看媒体文件的持续时间和追踪当前位置。

简介

tqdm 是一个 Python 快速、可扩展的进度条工具,它的名字来源于阿拉伯语 “taqaddum”(تقدّم),意思是"进步"。这个模块可以让你在循环或长时间运行的操作中添加一个智能进度条,让用户清楚地知道程序执行的进度。

主要特点

  1. 简单易用:只需在可迭代对象外包装 tqdm 即可
  2. 低开销:对性能影响极小
  3. 高度可定制:可以自定义进度条的样式、更新频率等
  4. 跨平台:支持命令行、Jupyter Notebook 等多种环境
  5. 多功能:支持手动更新、嵌套进度条等高级功能

安装

  • 使用 pip 安装:

    1
    pip install tqdm
  • 或者 conda:

    1
    conda install -c conda-forge tqdm

基本用法

  1. 基本循环

    1
    2
    3
    4
    5
    from tqdm import tqdm
    import time

    for i in tqdm(range(100)):
    time.sleep(0.1) # 模拟耗时操作
  2. 描述性进度条

    1
    2
    for i in tqdm(range(100), desc="处理进度"):
    time.sleep(0.1)
  3. 手动更新

    1
    2
    3
    4
    5
    pbar = tqdm(total=100)
    for i in range(10):
    time.sleep(0.1)
    pbar.update(10) # 每次更新10
    pbar.close()

高级功能

  1. 嵌套进度条

    1
    2
    3
    4
    5
    6
    from tqdm import trange
    import time

    for i in trange(3, desc='外层循环'):
    for j in trange(100, desc='内层循环', leave=False):
    time.sleep(0.01)
  2. Pandas 集成

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import pandas as pd
    from tqdm import tqdm

    # 注册pandas进度条
    tqdm.pandas()

    # 现在DataFrame的apply操作会显示进度条
    df = pd.DataFrame({"x": range(10000)})
    df["y"] = df["x"].progress_apply(lambda x: x**2)
  3. 自定义格式

    1
    2
    3
    4
    for i in tqdm(
    range(100), bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]"
    ):
    time.sleep(0.1)

常见参数详解

  • 基本控制参数

    1. iterable (可选)
      • 要包装的可迭代对象
      • 如果省略,需要手动使用 update() 方法
    2. desc (str, 可选)
      • 进度条前面的描述文字
      • 示例: desc="Processing"
    3. total (int/float, 可选)
      • 预期迭代次数
      • 如果未指定,会尝试从可迭代对象获取长度
    4. leave (bool, 可选)
      • 进度完成后是否保留进度条
      • 默认: True
      • 在嵌套进度条中内层通常设为 False
  • 显示控制参数

    1. ncols (int, 可选)
      • 进度条宽度(字符数)
      • 默认: None (自动调整)
    2. mininterval (float, 可选)
      • 进度条最小更新间隔(秒)
      • 默认: 0.1
    3. maxinterval (float, 可选)
      • 进度条最大更新间隔(秒)
      • 默认: 10.0
    4. miniters (int/float, 可选)
      • 最小更新迭代次数
      • 默认: None (自动调整)
    5. ascii (bool/str, 可选)
      • 是否使用ASCII字符
      • 可以指定自定义字符串,如 " ▏▎▍▌▋▊▉█"
    6. disable (bool, 可选)
      • 是否禁用整个进度条
      • 默认: False
  • 格式控制参数

    1. unit (str, 可选)
      • 迭代单位名称
      • 默认: “it” (iteration)
      • 示例: unit="file" 会显示 “file/s” 而不是 “it/s”
    2. unit_scale (bool/int/float, 可选)
      • 自动缩放单位 (如 K, M, G)
      • 默认: False
      • 示例: unit_scale=True 会将 1000 显示为 1K
    3. dynamic_ncols (bool, 可选)
      • 根据环境动态调整进度条宽度
      • 默认: False
    4. bar_format (str, 可选)
      • 自定义进度条格式
      • 可用变量:
        • {l_bar}: 左部分 (描述+百分比)
        • {bar}: 进度条本身
        • {r_bar}: 右部分 (计数+时间)
        • {n_fmt}: 当前步数
        • {total_fmt}: 总步数
        • {elapsed}: 已用时间
        • {remaining}: 剩余时间
        • {rate_fmt}: 速率
      • 示例: "{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]"
  • 文件输出参数

    1. file (io.TextIOWrapper/io.StringIO, 可选)
      • 输出位置
      • 默认: sys.stderr
    2. position (int, 可选)
      • 指定进度条位置(行偏移)
      • 用于多个进度条排列
  • 颜色参数 (部分环境支持)

    1. colour (str, 可选)
      • 进度条颜色
      • 示例: “green”, “#00ff00”, “rgb(0,255,0)”

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
from tqdm import tqdm
import time

# 综合使用多个参数
for i in tqdm(range(100),
desc="处理进度",
total=100,
ncols=80,
unit="文件",
unit_scale=True,
colour="green",
bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]"):
time.sleep(0.1)

简介

progress 是 Python 中另一个用于创建进度条的库,它提供了多种风格的进度条实现。与 tqdm 相比,progress 提供了更多样化的进度条样式选择,适合需要不同视觉风格的项目。

主要特点

  1. 多种进度条样式:提供多种预定义的进度条样式
  2. 简单易用:API 设计简洁直观
  3. 自定义灵活:支持自定义进度条外观
  4. 轻量级:依赖少,对项目影响小

安装

1
pip install progress

主要进度条类型

  1. Bar - 基本进度条

    1
    2
    3
    4
    5
    6
    7
    8
    from progress.bar import Bar
    import time

    bar = Bar("Processing", max=20)
    for i in range(20):
    time.sleep(0.1)
    bar.next()
    bar.finish()
  2. ChargingBar - 动态充电样式

    1
    2
    3
    4
    5
    6
    7
    8
    import time
    from progress.bar import ChargingBar

    bar = ChargingBar("Charging", max=20)
    for i in range(20):
    time.sleep(0.1)
    bar.next()
    bar.finish()
  3. FillingSquaresBar - 方块填充样式

    1
    2
    3
    4
    5
    6
    7
    8
    import time
    from progress.bar import FillingSquaresBar

    bar = FillingSquaresBar("Filling", max=20)
    for i in range(20):
    time.sleep(0.1)
    bar.next()
    bar.finish()
  4. FillingCirclesBar - 圆圈填充样式

    1
    2
    3
    4
    5
    6
    7
    8
    import time
    from progress.bar import FillingCirclesBar

    bar = FillingCirclesBar("Circles", max=20)
    for i in range(20):
    time.sleep(0.1)
    bar.next()
    bar.finish()
  5. IncrementalBar - 增量样式

    1
    2
    3
    4
    5
    6
    7
    8
    import time
    from progress.bar import IncrementalBar

    bar = IncrementalBar("Countdown", max=20)
    for i in range(20):
    time.sleep(0.1)
    bar.next()
    bar.finish()
  6. PixelBar - 像素风格

    1
    2
    3
    4
    5
    6
    7
    8
    import time
    from progress.bar import PixelBar

    bar = PixelBar("Pixels", max=20)
    for i in range(20):
    time.sleep(0.1)
    bar.next()
    bar.finish()
  7. Spinner - 旋转指示器(不确定进度时使用)

    1
    2
    3
    4
    5
    6
    7
    import time
    from progress.spinner import Spinner

    spinner = Spinner("Loading ")
    for i in range(50):
    time.sleep(0.1)
    spinner.next()

常见参数

  1. message (str): 进度条前的消息文本
  2. max (int): 总迭代次数
  3. suffix (str): 进度条后的后缀文本
  4. width (int): 进度条宽度(字符数)
  5. fill (str): 填充字符
  6. empty_fill (str): 空白部分填充字符
  7. bar_prefix (str): 进度条前缀字符
  8. bar_suffix (str): 进度条后缀字符

自定义进度条

你可以通过继承 Bar 类来创建自定义进度条:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import time
from progress.bar import Bar


class CustomBar(Bar):
suffix = "%(percent).1f%% - %(eta)ds"
bar_prefix = "["
bar_suffix = "]"
empty_fill = "."
fill = "#"


bar = CustomBar("Custom", max=20)
for i in range(20):
time.sleep(0.1)
bar.next()
bar.finish()

简介

alive-progress 是一个功能丰富且高度可定制的 Python 进度条库,以其动态、生动的视觉效果而著称。相比 tqdmprogress,它提供了更炫酷的动画效果和更强大的自定义能力。

主要特点

  1. 动态动画效果:与传统的静态进度条不同,alive-progress 提供了各种动态旋转器和条形图动画
  2. 实时吞吐量统计:显示处理速度(单位/秒)和预计剩余时间
  3. 高度可定制:可以调整进度条样式、动画效果、统计信息等
  4. 无需手动更新:使用上下文管理器或迭代器包装,自动处理进度更新
  5. 支持 Jupyter Notebook:在笔记本环境中也能良好工作

安装方法

1
pip install alive-progress

基本用法

1
2
3
4
5
6
7
from alive_progress import alive_bar
import time

with alive_bar(100) as bar: # 指定总数为100
for i in range(100):
time.sleep(0.03) # 模拟工作
bar() # 更新进度

迭代器用法

1
2
3
4
5
import time
from alive_progress import alive_it

for i in alive_it(range(100)):
time.sleep(0.03) # 模拟工作

高级功能

  1. 自定义外观

    1
    2
    3
    4
    5
    6
    7
    import time
    from alive_progress import alive_bar

    with alive_bar(100, bar="filling", spinner="waves") as bar:
    for i in range(100):
    time.sleep(0.03)
    bar()
  2. 添加标题和单位

    1
    2
    3
    4
    5
    6
    7
    import time
    from alive_progress import alive_bar

    with alive_bar(100, title="Processing", unit="files") as bar:
    for i in range(100):
    time.sleep(0.03)
    bar()
  3. 无总数模式(当总数未知时)

    1
    2
    3
    4
    5
    6
    7
    from alive_progress import alive_bar


    with alive_bar(unknown=True) as bar:
    for item in long_running_process():
    process(item)
    bar()

常见参数

  1. total (int): 总任务数
  2. title (str): 进度条标题
  3. bar (str): 进度条样式 (‘solid’, ‘filling’, 'classic’等)
  4. spinner (str): 旋转动画样式 (‘dots’, ‘waves’, 'twirls’等)
  5. theme (str): 内置主题 (‘ascii’, ‘smooth’, 'scuba’等)
  6. length (int): 进度条长度
  7. spinner_length (int): 旋转动画长度
  8. enrich_print (bool): 是否美化print输出
  9. manual (bool): 是否手动控制模式
  10. monitor (bool): 是否显示系统监控信息

动画样式预览

你可以使用以下命令查看所有可用样式:

1
2
from alive_progress.styles import showtime
showtime() # 显示所有可用的动画样式
本文结束 感谢您的阅读
正在加载今日诗词....