이 섹션에서는 Linux 터미널에서 서식이 지정된 텍스트를 인쇄하는 방법을 살펴봅니다. 서식을 지정하여 텍스트 색상, 스타일 및 일부 특수 기능을 변경할 수 있습니다.
Linux 터미널은 형식, 색상 및 기타 기능을 제어하기 위해 일부 ANSI 이스케이프 시퀀스를 지원합니다. 따라서 텍스트에 일부 바이트를 포함해야 합니다. 따라서 터미널이 해석을 시도할 때 해당 형식이 적용됩니다.
ANSI 이스케이프 시퀀스의 일반 구문은 다음과 같습니다. -
\x1b[A;B;C
- A는 텍스트 서식 스타일입니다.
- B는 텍스트 색상 또는 전경 색상입니다.
- C는 배경색입니다.
A, B, C에 대해 미리 정의된 값이 있습니다. 이들은 아래와 같습니다.
텍스트 서식 스타일(A형)
| 값 | 스타일 |
|---|---|
| 1 | 굵게 |
| 2 | 기절 |
| 3 | 기울임꼴 |
| 4 | 밑줄 |
| 5 | 깜박임 |
| 6 | 첫 번째 깜박임 |
| 7 | 역방향 |
| 8 | 숨기기 |
| 9 | 취소선 |
B 및 C 유형의 색상 코드입니다.
| 값(B) | 값(c) | 스타일 |
|---|---|---|
| 30 | 40 | 검정 |
| 31 | 41 | 빨간색 |
| 32 | 42 | 녹색 |
| 33 | 43 | 노란색 |
| 34 | 44 | 파란색 |
| 35 | 45 | 자홍색 |
| 36 | 46 | 청록 |
| 37 | 47 | 흰색 |
예시 코드
class Terminal_Format:
Color_Code = {'black' :0, 'red' : 1, 'green' : 2, 'yellow' : 3, 'blue' : 4, 'magenta' : 5, 'cyan' : 6, 'white' : 7}
Format_Code = {'bold' :1, 'faint' : 2, 'italic' : 3, 'underline' : 4, 'blinking' : 5, 'fast_blinking' : 6, 'reverse' : 7, 'hide' : 8, 'strikethrough' : 9}
def __init__(self): #reset the terminal styling at first
self.reset_terminal()
def reset_terminal(self): #Reset the properties
self.property = {'text_style' : None, 'fg_color' : None, 'bg_color' : None}
return self
def config(self, style = None, fg_col = None, bg_col = None): #Set all properties
return
self.reset_terminal().text_style(style).foreground(fg_col).background(bg_col)
def text_style(self, style): #Set the text style
if style in self.Format_Code.keys():
self.property['text_style'] = self.Format_Code[style]
return self
def foreground(self, fg_col): #Set the Foreground Color
if fg_colinself.Color_Code.keys():
self.property['fg_color'] = 30 + self.Color_Code[fg_col]
return self
def background(self, bg_col): #Set the Background Color
if bg_colinself.Color_Code.keys():
self.property['bg_color'] = 40 + self.Color_Code[bg_col]
return self
def format_terminal(self, string):
temp = [self.property['text_style'],self.property['fg_color'], self.property['bg_color']]
temp = [ str(x) for x in temp if x isnotNone ]
# return formatted string
return'\x1b[%sm%s\x1b[0m' % (';'.join(temp), string) if temp else string
def output(self, my_str):
print(self.format_terminal(my_str))
출력
<중앙>
스크립트를 실행하려면 터미널에서 Python 셸을 열고 스크립트에서 클래스를 가져와야 합니다.
해당 클래스의 객체를 생성한 후 원하는 결과를 얻도록 구성해야 합니다. 터미널 설정을 변경할 때마다 config() 함수를 사용하여 설정해야 합니다.