콘텐츠로 건너뛰기
Home » 터미널에 컬러로 문자열을 출력해보자 (Python)

터미널에 컬러로 문자열을 출력해보자 (Python)

터미널 상에 결과를 찍어주는 간단한 프로그램을 만들 때,  특정 단어나 문장에 색을 넣어 출력하고 싶을 때가 있다. 이를 위한 Colorama 라는 패키지도 따로 있기는 한데, 사실 터미널에서 색을 입혀서 출력하는 것은 ANSI 제어 문자를 이용해서 할 수 있는 부분이라 직접 만들어 보기로 한다.

터미널에서 사용할 수 있는 색상은 흰색과 검정 및 디폴트값을 제외하고 6개 색상이 있다. (빨강, 파랑, 녹색, 노랑, 마젠타, 시안) 이들은 각각 전경색(글자색)과 배경색에 적용할 수 있고, 전경색의 경우에는 어둡게, 밝게, 보통의 세 가지 옵션을 가질 수 있다. 따라서 색을 입히고자 하는 문자열의 앞/뒤에 이러한 ANSI 제어 코드를 붙여주면 컬러로 색을 입힐 수 있다.
아래는 작성된 코드의 GIST 이고


COLORS = dict(zip(range(1, 10), 'black red green yellow blue magenta'
' cyan white reset'.split()))
class BG:
black = '\033[40m'
red = '\033[41m'
green = '\033[42m'
yellow = '\033[43m'
blue = '\033[44m'
magenta = '\033[45m'
cyan = '\033[46m'
white = '\033[47m'
reset = '\033[49m'
class FG:
black = '\033[30m'
red = '\033[31m'
green = '\033[32m'
yellow = '\033[33m'
blue = '\033[34m'
magenta = '\033[35m'
cyan = '\033[36m'
white = '\033[37m'
reset = '\033[39m'
class BRIGHT:
bright = '\033[1m'
dim = '\033[2m'
normal = '\033[22m'
class Color:
resetall = '\033[0m'
@classmethod
def colored(self, msg, foreground='white', background='black', bright=0):
xBRIGHT, xBG, xFG = '', '', ''
if bright is 1:
xBRIGHT = BRIGHT.bright
elif bright is 2:
xBRIGHT = BRIGHT.dim
else:
xBRIGHT = BRIGHT.normal
if hasattr(BG, background):
xBG = getattr(BG, background)
if hasattr(FG, foreground):
xFG = getattr(FG, foreground)
return '{}{}{}{}{}'.format(
xBRIGHT, xBG, xFG, msg, Color.resetall)
if __name__ == '__main__':
msg = input('>>> ')
colors = list(COLORS.values())
for i in range(0, len(colors), 3):
for fg in colors:
line = ' '.join([''.join(Color.colored(msg, fg, colors[i+x], y)
for y in (1, 2, 0))
for x in range(3)])
print(line)
print()

view raw

colorprint.py

hosted with ❤ by GitHub

대충 이런식으로 출력할 수 있다.

데모 출력 화면
데모 출력 화면