標準出力したい(rich)
1from rich import print
2print("Hello, [bold magenta]Rich[/bold magenta]!")
richは、Pythonの標準出力を装飾するためのライブラリです。
インストールしたい(rich)
pipでインストール
$ python3 -m venv .venv
$ source .venv/bin/activate
$ pip install rich
uvでプロジェクトに追加
$ uv add rich
poetryでプロジェクトに追加
$ poetry add rich
注釈
richはCLIツールではなくライブラリなので、
pipxやuv toolではなく、プロジェクトの依存関係として追加します。
rich.print関数に置き換えるだけで、テキストの色やスタイルを指定して、見やすく、わかりやすい出力を実現できます。
注釈
from rich import printは、Pythonの組み込み関数printを
rich.printで上書き(シャドーイング)しています。
そのファイル内では以降print(...)と書くだけで、装飾された出力が使えるようになります。
[スタイル名]テキスト[/スタイル名]のようなタグで、テキストにスタイルを指定できます。
bold(太字)、red・green・magentaなどの色名、
italic(斜体)、underline(下線)などを組み合わせて使えます
(例:[bold red]エラー[/bold red])。
コンソール出力したい(rich.console.Console)
1import sys
2from rich.console import Console
3stdout = Console(file=sys.stdout)
4stderr = Console(file=sys.stderr)
5
6stdout.print("This is a message to standard output.", style="green")
7stderr.print("This is a message to standard error.", style="red")
rich.console.Consoleを使って、標準出力や標準エラーに装飾されたテキストを出力できます。
Consoleオブジェクトを作成するときに、file引数で出力先を変更できます。
システムの標準出力(sys.stdout)や標準エラー出力(sys.stderr)を指定するのが最近の個人的なお気に入りです。
注釈
richには、このほかにもテーブル(rich.table.Table)、
進捗バー(rich.progress)、
トレースバックの装飾(rich.traceback)、
標準のloggingモジュールと連携するRichHandler(rich.logging)など、
数多くの機能があります。
くわしくは公式ドキュメントを参照してください。
テーブル表示したい(rich.table.Table)
1from rich.console import Console
2from rich.table import Table
3
4console = Console()
5table = Table(title="ユーザー一覧")
6
7table.add_column("名前", style="cyan")
8table.add_column("年齢", justify="right", style="magenta")
9table.add_column("役職", style="green")
10
11table.add_row("Alice", "30", "Engineer")
12table.add_row("Bob", "25", "Designer")
13
14console.print(table)
rich.table.Tableで、装飾されたテーブルをコンソールに表示できます。
add_columnで列を定義し、add_rowで行を追加します。
style引数で列ごとに色を指定でき、justifyで文字寄せ(left・center・right)を指定できます。
進捗バーしたい(rich.progress)
1import time
2from rich.progress import track
3
4for i in track(range(20), description="処理中..."):
5 time.sleep(0.1) # なんらかの処理
rich.progress.trackで、for文をそのまま進捗バー付きのループに変換できます。
rangeやlistなどのイテラブルをラップするだけで使えます。
より細かく制御したい場合はrich.progress.Progressを使います。
1import time
2from rich.progress import Progress
3
4with Progress() as progress:
5 task1 = progress.add_task("[cyan]ダウンロード中...", total=100)
6 task2 = progress.add_task("[green]処理中...", total=50)
7
8 while not progress.finished:
9 progress.update(task1, advance=1)
10 progress.update(task2, advance=0.5)
11 time.sleep(0.05)
Progressオブジェクトで複数の進捗バーを同時に表示できます。
add_taskで進捗バーを追加し、updateで進捗を更新します。