LoginSignup
180
131

More than 5 years have passed since last update.

tqdmでプログレスバーを表示させる

Posted at

環境

macOS 10.14.2
python 3.6.3

下準備

はじめにtqdmをインストールしておきます.

$ pip install tqdm

基本

下のコードは100回のループを回していて, 各ループごとに1秒の間隔を空けて実行しています.
その処理にtqdmを使用して, プログレスバーを導入します. range()関数の値をtqdm()関数に与えるだけでプログレスバーを表示することができます.
100回分のループを渡しているので, 1回のループで1%の進捗があります.

# coding: utf-8
from tqdm import tqdm
import time

for i in tqdm(range(100)):
    time.sleep(1)
#100%|██████████| 100/100 [01:40<00:00,  1.00s/it]

range()関数以外にもリストや文字列を渡すことができます.

# coding: utf-8
from tqdm import tqdm
import time

for i in tqdm([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]):
    time.sleep(1)
#100%|██████████| 10/10 [00:10<00:00,  1.00s/it]
# coding: utf-8
from tqdm import tqdm
import time

for i in tqdm('Time is money!'):
    time.sleep(1)
#100%|██████████| 14/14 [00:14<00:00,  1.00s/it]

update

update()を使うことで, 自分で進捗率を設定することができます.
まず, 合計値(total)を設定します. そしてupdate()で進捗を設定します.
下のコードでは, 合計値を1000, 1回のループの進捗を10に設定しています.

# coding: utf-8
from tqdm import tqdm
import time

# 合計値(total)を設定
bar = tqdm(total = 1000)
for i in range(100):
    # 進捗を設定
    bar.update(10)
    time.sleep(1)
#100%|██████████| 1000/1000 [01:39<00:00,  9.96it/s]

説明文を加える

set_description()を用いることで, 説明文を設定できることができます.

# coding: utf-8
from tqdm import tqdm
import time

# 合計値(total)を設定
bar = tqdm(total = 1000)
# 説明文を追加
bar.set_description('Progress rate')
for i in range(100):
    # 進捗を設定
    bar.update(10)
    time.sleep(1)
#Progress rate: 100%|██████████| 1000/1000 [01:39<00:00,  9.98it/s]
180
131
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
180
131