【Python】出力に色をつける

Pythonで出力に色をつけるにはtermcolorモジュールを使用します。
termcolor

コンソールアプリケーションで、ユーザーに見逃してほしくない情報に赤色などで着色して、
目立たせたいときなどに役立ちます。

termcolorの使用方法

termcolorをインストールするにはpipまたはcondaコマンドを使用します。

1pip install termcolor
1import termcolor
2
3warning_sentence = termcolor.colored('Warning', 'red')
4print(warning_sentence)

termcolorモジュールをインポートし、coloredメソッドを使用して文字列に色をつけます。

上記のコードはWarningという文字に赤を着色して出力します。

赤以外にも色をつけることができます。
赤を警告(Warning)、黄色を注意(Caution)、緑色を通知(Notice)で出力し、str.formatを利用して、飾り付けて出力してみます。

 1import termcolor
 2
 3# 警告(Warning)
 4warning = '*' * 30 + '\n'
 5warning += '*{:^28}*\n'.format('Warning')
 6warning += '*' * 30 + '\n'
 7colored_warning = termcolor.colored(warning, 'red')
 8print(colored_warning)
 9
10# 黄色(Caution)
11caution = '+' * 30 + '\n'
12caution += '+{:^28}+\n'.format('Caution')
13caution += '+' * 30 + '\n'
14colored_warning = termcolor.colored(caution, 'yellow')
15print(colored_warning)
16
17# 通知(Notice)
18notice = '-' * 30 + '\n'
19notice += '|{:^28}|\n'.format('Notice')
20notice += '-' * 30 + '\n'
21colored_warning = termcolor.colored(notice, 'green')
22print(colored_warning)

各文字列の出力結果は以下のようになります。

使用できる色の一覧はPyPIのtermcolorパッケージのページに記載されていますので、参照してみて下さい。 https://pypi.org/project/termcolor

関連ページ