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 は最も人気のあるプログレスバーライブラリの1つで、インストールも簡単で使いやすいです。

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