在 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))

输出

Linux Terminal

要运行脚本,我们应该在终端中打开 Python shell,然后我们将从脚本中导入类。

在创建该类的对象后,我们必须进行配置以获得所需的结果。每次我们想要更改终端设置时,都必须使用 config() 函数对其进行配置。

更新于: 2019年7月30日

249 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告