Formatted text in Linux Terminal using Python



In this section, we will see how to print formatted texts in Linux terminal. By formatting, we can change the text color, style, and some special features.

Linux terminal supports some ANSI escape sequences to control the formatting, color and other features. So we have to embed some bytes with the text. So when the terminal is trying to interpret them, those formatting will be effective.

The general syntax of ANSI escape sequence is like below −

 \x1b[A;B;C 
  • A is the Text Formatting Style
  • B is the Text Color or Foreground Color
  • C is the Background Color

There are some Predefined values for A, B and C. These are like below.

The Text Formatting Style (Type A)

Values Style
1 Bold
2 Faint
3 Italic
4 Underline
5 Blinking
6 First Blinking
7 Reverse
8 Hide
9 Strikethrough

The Color Code for type B and C.

Values(B) Values(c) Style
30 40 Black
31 41 Red
32 42 Green
33 43 Yellow
34 44 Blue
35 45 Magenta
36 46 Cyan
37 47 White

Example code

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

Output

Linux Terminal

To run the Script, we should open the Python shell in Terminal, and after that we will import the class from the script.

After creating an object of that class, we have to configure to get the desired result. Each time when we want to change the terminal setting, we have to configure it using config() function.

Updated on: 2019-07-30T22:30:23+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements