python實現控制臺輸出顏色
本文實例為大傢分享瞭python實現控制臺輸出顏色的具體代碼,供大傢參考,具體內容如下
python控制臺輸出顏色,out()是基本方法,還封裝瞭一些基本顏色方法,如red(),blue(),green()等
out()方法的color參數表示顏色,bgcolor表示背景顏色,style表示樣式
其他方法的參數類似,三個參數的具體取值封裝到Color類,BGColor類,Style類中。
基本方法:
out(content, color=Color.DEFAULT, bgcolor=BGColor.DEFAULT, style=Style.DEFAULT) red (content [, bgcolor, [style]]) green (content [, bgcolor, [style]]) blue (content [, bgcolor, [style]]) yellow (content [, bgcolor, [style]]) bold (content [, color, [bgcolor]]) underline (content [, color, [bgcolor]]) italic (content [, color, [bgcolor]])
具體代碼:
from functools import partial class Style: DEFAULT = 0 BOLD= 1 ITALIC = 3 UNDERLINE = 4 ANTIWHITE = 7 class Color: DEFAULT = 39 BLACK = 30 RED = 31 GREEN = 32 YELLOW = 33 BLUE = 34 PURPLE = 35 CYAN = 36 WHITE = 37 LIGHTBLACK_EX = 90 LIGHTRED_EX = 91 LIGHTGREEN_EX = 92 LIGHTYELLOW_EX = 93 LIGHTBLUE_EX = 94 LIGHTMAGENTA_EX = 95 LIGHTCYAN_EX = 96 LIGHTWHITE_EX = 97 class BGColor: DEFAULT = 49 BLACK = 40 RED = 41 GREEN = 42 YELLOW = 43 BLUE = 44 PURPLE = 45 CYAN = 46 WHITE = 47 LIGHTBLACK_EX = 100 LIGHTRED_EX = 101 LIGHTGREEN_EX = 102 LIGHTYELLOW_EX = 103 LIGHTBLUE_EX = 104 LIGHTMAGENTA_EX = 105 LIGHTCYAN_EX = 106 LIGHTWHITE_EX = 107 def out(content, color=Color.DEFAULT, bgcolor=BGColor.DEFAULT, style=Style.DEFAULT): print("\033[{};{};{}m{}\033[0m".format(style, color, bgcolor, content)) red = partial(out, color=Color.RED) green = partial(out, color=Color.GREEN) blue = partial(out, color=Color.BLUE) yellow = partial(out, color=Color.YELLOW) bold = partial(out, style=Style.BOLD) underline = partial(out, style=Style.UNDERLINE) italic = partial(out, style=Style.ITALIC)
紅綠燈事件輸出顏色示例:
from multiprocessing import Event, Process import time import random from basicPractice import outputscreen # 這裡導入瞭上面寫的模塊 def car(event: Event, i: int): if not event.is_set(): outputscreen.out('car{}等待'.format(i), bgcolor=outputscreen.BGColor.RED) event.wait() else: outputscreen.out('car{}通行'.format(i), bgcolor=outputscreen.BGColor.GREEN) def light(event: Event): while True: if not event.is_set(): outputscreen.red('紅燈亮瞭', style=outputscreen.Style.BOLD) time.sleep(1) event.set() else: outputscreen.green('綠燈亮瞭', style=outputscreen.Style.BOLD) time.sleep(3) event.clear() if __name__ == '__main__': event = Event() p = Process(target=light, args=(event,)) p.start() for i in range(20): Process(target=car, args=(event, i)).start() time.sleep(random.random())
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- 鼠標劃過時整行變色284278過程講解
- Python docx庫刪除復制paragraph及行高設置圖片插入示例
- Pygame Font模塊使用教程
- Python全棧之學習CSS(1)
- 利用Python中xlwt模塊操作excel的示例詳解