Python/Python Basic

Python Basic : Terminal 글자 색상, 배경 색상 입히기

CosmosProject 2024. 3. 21. 19:31
728x90
반응형

 

 

 

Python에서는 Terminal에 어떤 글자를 출력할 때 내가 원하는 글자의 색상, 그리고 배경색을 선택할 수 있는 기능을 제공합니다.

  

print('\033[38;2;120;150;80mapple\033[0m')

 

위 코드를 실행하면 아래처럼 초록색 글씨고 apple이 출력됩니다.

 

 

 

 

 

print('\033[38;2;120;150;80mapple\033[0m')

\033 ~ \033 -> color setting section을 의미.
38 -> Text color를 조절할 것이라는 의미.
2 -> RGB color를 사용할 것이라는 의미.
120 -> R
180 -> G
80 -> B
m -> Setting
apple -> Showing text
[0m -> Reset color setting to default

 

위 구문의 각 부분에 대한 의미는 위와 같습니다.

이를 이용하면 Text color를 마음대로 조절할 수 있습니다.

 

 

 

 

print('\033[48;2;120;150;80mapple\033[0m')

 

위 코드를 실행하면 아래와 같은 결과가 나옵니다.

 

 

이번에는 배경 색이 채워졌습니다.

 

 

print('\033[48;2;120;150;80mapple\033[0m')

\033 ~ \033 -> color setting section을 의미.
48 -> Background color를 조절할 것이라는 의미.
2 -> RGB color를 사용할 것이라는 의미.
120 -> R
180 -> G
80 -> B
m -> Setting
apple -> Showing text
[0m -> Reset color setting to default

 

중요한 것은 48을 사용했다는 것인데 이것은 Text background color를 조절하겠다는 의미입니다.

 

 

 

 

 

 

print('\033[48;2;120;150;80mapple\033')
print('asoduhfousdhg')

 

만약 [0m이라는 setting reset 문구를 입력해주지 않으면

아래처럼 색상 설정 후 출력되는 모든 텍스트에 color setting이 적용됩니다.

 

 

 

 

 

 

 

 

아래는 랜덤한 색상을 입히는 코드 예시입니다.

 

import numpy as np

R = np.random.randint(0, 256)
G = np.random.randint(0, 256)
B = np.random.randint(0, 256)

def coloring_text(tb_flag, r, g, b, text):
    val_tb = 38
    if tb_flag == 'text':
        val_tb = 38
    if tb_flag == 'background':
        val_tb = 48

    val_colored_text = '\033[{tb_flag};2;{r};{g};{b}m{text}\033[0m'.format(
        tb_flag=val_tb,
        r=r,
        g=g,
        b=b,
        text=text
    )
    print(val_colored_text)

for i in range(100):
    coloring_text(tb_flag='background',
                  r=np.random.randint(0, 256),
                  g=np.random.randint(0, 256),
                  b=np.random.randint(0, 256),
                  text='First')
    coloring_text(tb_flag='background',
                  r=np.random.randint(0, 256),
                  g=np.random.randint(0, 256),
                  b=np.random.randint(0, 256),
                  text='Second')
    print('')

 

 

 

 

 

 

 

 

728x90
반응형