इस सेक्शन में, हम देखेंगे कि 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):
self.reset_terminal()
def reset_terminal(self):
self.property = {'text_style': None, 'fg_color': None, 'bg_color': None}
return self
def config(self, style=None, fg_col=None, bg_col=None):
return self.reset_terminal().text_style(style).foreground(fg_col).background(bg_col)
def text_style(self, style):
if style in self.Format_Code.keys():
self.property['text_style'] = self.Format_Code[style]
return self
def foreground(self, fg_col):
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):
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 '\x1b[%sm%s\x1b[0m' % (';'.join(temp), string) if temp else string
def output(self, my_str):
print(self.format_terminal(my_str))
आउटपुट

स्क्रिप्ट चलाने के लिए, हमें टर्मिनल में Python शेल खोलना चाहिए, और उसके बाद स्क्रिप्ट से क्लास इम्पोर्ट करनी चाहिए।
उस क्लास का ऑब्जेक्ट बनाने के बाद, हमें वांछित परिणाम प्राप्त करने के लिए कॉन्फ़िगर करना होगा। हर बार जब हम टर्मिनल सेटिंग बदलना चाहते हैं, तो हमें config() फ़ंक्शन का उपयोग करके इसे कॉन्फ़िगर करना होगा।