在 Linux 終端使用 Python 格式化文字
在本節中,我們將瞭解如何在 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 shell,然後我們將從指令碼中匯入類。
在建立該類的物件後,我們必須進行配置以獲得所需的結果。每次我們想要更改終端設定時,都必須使用 config() 函式對其進行配置。
廣告