使用 Python 在 Linux 终端中格式化文本
pythonprogrammingserver side programming更新于 2024/3/27 10:10:00
在本节中,我们将了解如何在 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 | 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): #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() 函数对其进行配置。