Trong phần này, chúng ta sẽ xem cách in văn bản định dạng trong terminal Linux. Bằng cách định dạng, chúng ta có thể thay đổi màu văn bản, kiểu dáng và một số tính năng đặc biệt.
Terminal Linux hỗ trợ một số chuỗi thoát ANSI để kiểm soát định dạng, màu và các tính năng khác. Vì vậy chúng ta phải nhúng một số byte với văn bản. Vì vậy khi terminal cố gắng diễn giải chúng, các định dạng đó sẽ có hiệu lực.
Cú pháp chung của chuỗi thoát ANSI như sau:
\x1b[A;B;C
- A là Kiểu định dạng văn bản
- B là Màu văn bản hoặc Màu tiền cảnh
- C là Màu nền
Có một số giá trị được định nghĩa trước cho A, B và C. Chúng như sau:
Kiểu định dạng văn bản (Loại A)
| Giá trị | Kiểu |
|---|---|
| 1 | Đậm (Bold) |
| 2 | Nhạt (Faint) |
| 3 | Nghiêng (Italic) |
| 4 | Gạch dưới (Underline) |
| 5 | Nhấp nháy (Blinking) |
| 6 | Nhấp nháy nhanh (Fast Blinking) |
| 7 | Đảo ngược (Reverse) |
| 8 | Ẩn (Hide) |
| 9 | Gạch ngang (Strikethrough) |
Mã màu cho loại B và C:
| Giá trị (B) | Giá trị (C) | Kiểu |
|---|---|---|
| 30 | 40 | Đen |
| 31 | 41 | Đỏ |
| 32 | 42 | Xanh lá |
| 33 | 43 | Vàng |
| 34 | 44 | Xanh dương |
| 35 | 45 | Magenta |
| 36 | 46 | Cyan |
| 37 | 47 | Trắng |
Mã ví dụ
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 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_col in self.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_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 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))
Đầu ra

Để chạy Script, chúng ta nên mở Python shell trong Terminal, và sau đó nhập lớp từ script.
Sau khi tạo đối tượng của lớp đó, chúng ta phải cấu hình để lấy kết quả mong muốn. Mỗi khi chúng ta muốn thay đổi cài đặt terminal, chúng ta phải cấu hình nó sử dụng hàm config().