Programming/python

파이썬 - 출력 텍스트에 색상넣는 방법 | print() function with colored text in python

방황하는 데이터불도저 2022. 11. 17. 17:03

코드의 결과를 print() 함수로 출력해주다보면 뭔가 밋밋하고, 꾸며주고싶은 욕구가 샘솟는다.

그럴 때 딱 필요한 라이브러리 "colorama"를 소개해보겠다.

 

https://pypi.org/project/colorama/

 

colorama

Cross-platform colored terminal text.

pypi.org

 

우선, 아래의 커맨드로 colorama 라이브러리를 설치해준다.

pip install colorama
# or
conda install -c anaconda colorama

 

본격적인 예시이다.

  • Fore.COLOR : 글자색 변경 함수
  • Back.COLOR : 글자 배경색 변경 함수
  • Style.FEATURE : 글자 스타일 변경 함수
  • Style.RESET_ALL : 초기화
from colorama import Fore, Back, Style

print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.BRIGHT + 'and in dim text')

print(Style.RESET_ALL)
print('back to normal now')
print(Back.GREEN + 'and with a green background')
print(Style.BRIGHT + 'and in dim text')

그 결과, 이렇게 나온다.

 

* 각 함수별 지원 Colors와 Features

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL

 

이렇게 글 중간에도 사용할 수 있다.

import torch
from colorama import Fore, Back, Style

# Define the execution device
# cuda check
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("The model will be running on", Fore.RED+device, Style.RESET_ALL+"device")

# 결과

 

** 주의

원하는 style적용구간이 끝난 후에는 꼭 print(Style.RESET_ALL)을 해줘야한다.

이게 조금 귀찮긴하다....