Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ข้อความที่จัดรูปแบบใน Linux Terminal โดยใช้ Python


ในส่วนนี้ เราจะมาดูวิธีการพิมพ์ข้อความที่จัดรูปแบบในเทอร์มินัล Linux ด้วยการจัดรูปแบบ เราสามารถเปลี่ยนสีข้อความ ลักษณะ และคุณลักษณะพิเศษบางอย่างได้

เทอร์มินัล Linux รองรับ Escape Sequence ของ ANSI บางตัวเพื่อควบคุมการจัดรูปแบบ สี และคุณสมบัติอื่นๆ ดังนั้นเราต้องฝังบางไบต์กับข้อความ ดังนั้นเมื่อเทอร์มินัลพยายามแปลความหมาย การจัดรูปแบบเหล่านั้นจะมีผล

ไวยากรณ์ทั่วไปของลำดับหลีก ANSI มีลักษณะดังนี้ -

\x1b[A;B;C
  • A คือรูปแบบการจัดรูปแบบข้อความ
  • B คือสีข้อความหรือสีพื้นหน้า
  • C คือสีพื้นหลัง

มีค่าที่กำหนดไว้ล่วงหน้าสำหรับ A, B และ C ดังต่อไปนี้

รูปแบบการจัดรูปแบบข้อความ (ประเภท A)

ค่า สไตล์
1 ตัวหนา
2 เป็นลม
3 ตัวเอียง
4 ขีดเส้นใต้
5 กะพริบ
6 กะพริบครั้งแรก
7 ย้อนกลับ
8 ซ่อน
9 ขีดทับ

รหัสสีสำหรับประเภท B และ C

Values(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

ในการรันสคริปต์ เราควรเปิด Python shell ใน Terminal และหลังจากนั้นเราจะนำเข้าคลาสจากสคริปต์

หลังจากสร้างวัตถุของคลาสนั้นแล้ว เราต้องกำหนดค่าเพื่อให้ได้ผลลัพธ์ที่ต้องการ ทุกครั้งที่เราต้องการเปลี่ยนการตั้งค่าเทอร์มินัล เราต้องกำหนดค่าโดยใช้ฟังก์ชัน config()