Pythonメモ : haloでターミナルにスピナー(処理中)を表示
halo
haloというPythonでターミナルにスピナー(ローディング、処理中表示など)を表示するパッケージがあったので試してみる。
インストール
pip
でインストールできるので下記コマンドを実行。
$ pip install halo
実際はうまく動作しないものがあったのでGitHubのリポジトリをインストールした。
$ pip install git+https://github.com/ManrajGrover/halo
使い方
下記3つの使い方がある。
spinner.start()
とspinner.stop()
の間に時間のかかる処理を書く方法。
from halo import Halo import time spinner = Halo(text='Loading', spinner='dots') spinner.start() time.sleep(5) spinner.stop()
with
ステートメントも使う方法もある。
from halo import Halo import time with Halo(text='Loading', spinner='dots'): time.sleep(5)
デコレータも使える。
from halo import Halo import time @Halo(text='Loading', spinner='dots') def long_running_function(): time.sleep(5) pass long_running_function()
結果は全部同じ。
その他、examplesに使用例があったので見てみる。
frames
で表示するシンボルを指定できる。
spinner = Halo( text='Custom Spins', spinner={ 'interval': 100, 'frames': ['-', '+', '*', '+', '-'] } )
途中で色やシンボルを変更することも可能。
spinner.start() time.sleep(2) spinner.text = 'Much Colors' spinner.color = 'magenta' time.sleep(2) spinner.text = 'Very emojis' spinner.spinner = 'hearts' time.sleep(2) spinner.stop_and_persist({'symbol': '🦄 '.encode('utf-8'), 'text': 'Wow!'})
succeed()
やfail()
などもある。
success_message = 'Loading success' failed_message = 'Loading failed' unicorn_message = 'Loading unicorn' spinner = Halo(text=success_message, spinner='dots') spinner.start() time.sleep(1) spinner.succeed() spinner.start(failed_message) time.sleep(1) spinner.fail() spinner.start(unicorn_message) time.sleep(1) spinner.stop_and_persist({'symbol': '🦄 '.encode('utf-8'), 'text': unicorn_message})
参考:下記リポジトリが元ネタなのかな。
github.com