ในส่วนนี้เราจะดูวิธีพิมพ์ข้อความจัดรูปแบบใน Linux terminal ด้วยการจัดรูปแบบ เราสามารถเปลี่ยนสีข้อความ สไตล์ และคุณสมบัติพิเศษบางอย่างได้
Linux terminal รองรับ ANSI escape sequences สำหรับควบคุมการจัดรูปแบบ สี และคุณสมบัติอื่นๆ ดังนั้นเราต้องฝังไบต์บางส่วนกับข้อความ เมื่อ terminal พยายามตีความพวกมัน การจัดรูปแบบจะมีผล
ไวยากรณ์ทั่วไปของ ANSI escape sequence คือ:
\x1b[A;B;C
- A คือ Text Formatting Style
- B คือ Text Color หรือ Foreground Color
- C คือ Background Color
มีค่าที่กำหนดไว้ล่วงหน้าสำหรับ A, B และ C ดังนี้:
Text Formatting Style (Type A)
| ค่า | สไตล์ |
|---|---|
| 1 | Bold |
| 2 | Faint |
| 3 | Italic |
| 4 | Underline |
| 5 | Blinking |
| 6 | Fast Blinking |
| 7 | Reverse |
| 8 | Hide |
| 9 | Strikethrough |
Color Code สำหรับ type B และ C:
| ค่า (B) | ค่า (C) | สี |
|---|---|---|
| 30 | 40 | Black |
| 31 | 41 | Red |
| 32 | 42 | Green |
| 33 | 43 | Yellow |
| 34 | 44 | Blue |
| 35 | 45 | Magenta |
| 36 | 46 | Cyan |
| 37 | 47 | White |
ตัวอย่างโค้ด
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):
self.reset_terminal()
def reset_terminal(self):
self.property = {'text_style': None, 'fg_color': None, 'bg_color': None}
return self
def config(self, style=None, fg_col=None, bg_col=None):
return self.reset_terminal().text_style(style).foreground(fg_col).background(bg_col)
def text_style(self, style):
if style in self.Format_Code.keys():
self.property['text_style'] = self.Format_Code[style]
return self
def foreground(self, fg_col):
if fg_col in self.Color_Code.keys():
self.property['fg_color'] = 30 + self.Color_Code[fg_col]
return self
def background(self, bg_col):
if bg_col in self.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 is not None]
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 shell ใน Terminal หลังจากนั้น import คลาสจากสคริปต์ หลังจากสร้างออบเจ็กต์ของคลาสนั้น ต้อง config เพื่อให้ได้ผลลัพธ์ที่ต้องการ ทุกครั้งที่ต้องการเปลี่ยนการตั้งค่า terminal ต้อง config ด้วยฟังก์ชัน config()