Pythonで出力に色をつけるにはtermcolorモジュールを使用します。
コンソールアプリケーションで、ユーザーに見逃してほしくない情報に
赤色などで着色して、目立たせたいときなどに役立ちます。
termcolorの使用方法
termcolorをインストールするにはpipまたはcondaコマンドを使用します。
1 |
pip install termcolor |
1 |
conda install termcolor |
1 2 3 4 |
import termcolor warning_sentence = termcolor.colored('Warning', 'red') print(warning_sentence) |
termcolorモジュールをインポートし、coloredメソッドを使用して
文字列に色をつけます。
上記のコードはWarningという文字に赤を着色して出力します。
赤以外にも色をつけることができます。
赤を警告(Warning)、黄色を注意(Caution)、緑色を通知(Notice)で出力し
str.formatを利用して、飾り付けて出力してみます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import termcolor # 警告(Warning) warning = '*' * 30 + '\n' warning += '*{:^28}*\n'.format('Warning') warning += '*' * 30 + '\n' colored_warning = termcolor.colored(warning, 'red') print(colored_warning) # 黄色(Caution) caution = '+' * 30 + '\n' caution += '+{:^28}+\n'.format('Caution') caution += '+' * 30 + '\n' colored_warning = termcolor.colored(caution, 'yellow') print(colored_warning) # 通知(Notice) notice = '-' * 30 + '\n' notice += '|{:^28}|\n'.format('Notice') notice += '-' * 30 + '\n' colored_warning = termcolor.colored(notice, 'green') print(colored_warning) |
各文字列の出力結果は以下のようになります。
使用できる色の一覧はPyPIのtermcolorパッケージのページに
記載されていますので、参照してみて下さい。

termcolor
ANSI color formatting for output in terminal
コメント