惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
M
MIT News - Artificial intelligence
GbyAI
GbyAI
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
IT之家
IT之家
Microsoft Azure Blog
Microsoft Azure Blog
V
V2EX
爱范儿
爱范儿
N
Netflix TechBlog - Medium
U
Unit 42
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
博客园 - 叶小钗
G
Google Developers Blog
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
腾讯CDC

菜鸟教程

终端工具推荐 | 菜鸟教程 什么是张量? | 菜鸟教程 如何在 Windows 上将 Python 添加到 PATH Linux Cron 定时任务 | 菜鸟教程 REST API 教程 | 菜鸟教程 ChromeDriver 说明 | 菜鸟教程 pip 指定国内镜像,并设置不使用 https | 菜鸟教程 Trae 入门教程 | 菜鸟教程 Dify 零门槛打造专属 AI 应用 | 菜鸟教程 1.11 算法代码练习 | 菜鸟教程 解决 VS 编译中产生 C4996 错误的方式 中国大模型大全 | 菜鸟教程
Python 进度条 | 菜鸟教程
tianqixin · 2025-03-26 · via 菜鸟教程

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()