2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[メモ] Pythonで色付きprintを行うクラスを作成

Last updated at Posted at 2021-08-08

コード

一応,その他のPackage等ありますが,簡易クラスなら自分でも作成可能なのでメモ書きします.
ちなみにPackageの一つは colorama です.
Color codeはANSIに則って記述されます.

Main code

@shiracamus さんの意見を元にクラス変数を辞書に変更しました.
@shiracamus さんから引数のpython builtin print対応とモジュール化をしてはどうか?という提案がコメントに記載されております.(元内容を維持するために本文はそのまま変更しておりません.)

class pycolor:
    COLORS = dict(
        BLACK='\033[30m',
        RED='\033[31m',
        GREEN='\033[32m',
        YELLOW='\033[33m',
        BLUE='\033[34m',
        MAGENTA='\033[35m',
        CYAN='\033[36m',
        WHITE='\033[37m'
    )
    END = '\033[0m'

    @classmethod
    def print_(cls, txt: str, color='red') -> None:
        try:
            col = cls.COLORS[color.upper()]
            print(f'{col}{txt}{cls.END}')
        except KeyError:
            raise ValueError('color must be in {}, but got {}.'.format(', '.join(cls.COLORS.keys()), color.upper()))

Test code

pycolor.print_('Can you see it?', color='black')
>>> Can you see it? # Black string

pycolor.print_('Failed', color='red')
>>> Failed # Red string

pycolor.print_('OK', color='green')
>>> OK # Green string

pycolor.print_('Warning', color='yellow')
>>> Warning # Yellow string

pycolor.print_('Should be no color', color='block')
>>> ValueError: color must be in ['BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MAGENTA', 'CYAN', 'WHITE'], but got block.

その他のColor codes

前述のcoloramaで対応しているcolor codesは以下のとおりです.

ESC [ 0 m       # reset all (colors and brightness)
ESC [ 1 m       # bright
ESC [ 2 m       # dim (looks same as normal brightness)
ESC [ 22 m      # normal brightness

# FOREGROUND:
ESC [ 30 m      # black
ESC [ 31 m      # red
ESC [ 32 m      # green
ESC [ 33 m      # yellow
ESC [ 34 m      # blue
ESC [ 35 m      # magenta
ESC [ 36 m      # cyan
ESC [ 37 m      # white
ESC [ 39 m      # reset

# BACKGROUND
ESC [ 40 m      # black
ESC [ 41 m      # red
ESC [ 42 m      # green
ESC [ 43 m      # yellow
ESC [ 44 m      # blue
ESC [ 45 m      # magenta
ESC [ 46 m      # cyan
ESC [ 47 m      # white
ESC [ 49 m      # reset

# cursor positioning
ESC [ y;x H     # position cursor at x across, y down
ESC [ y;x f     # position cursor at x across, y down
ESC [ n A       # move cursor n lines up
ESC [ n B       # move cursor n lines down
ESC [ n C       # move cursor n characters forward
ESC [ n D       # move cursor n characters backward

# clear the screen
ESC [ mode J    # clear the screen

# clear the line
ESC [ mode K    # clear the line
2
3
6

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?