Python 在 Console 輸出顏色內容

MedusaSorcerer的博客


pypi.org/project/ter…python

不少開發的小夥伴都知道在利用 Python 在 Console 界面輸出顏色內容, 可是今天要介紹的是另外一種方式:shell

python -m pip install termcolor
複製代碼

你能夠直接這樣使用它:spa

#!/usr/bin/env python
# _*_ Coding: UTF-8 _*_
from termcolor import cprint

cprint('color', 'red', attrs=['reverse', 'blink'])
複製代碼

你在 Pycharm 獲得的結果就是: 3d

固然了, 這種方式在 Windows-CMD 上就顯得不那麼實用:
若是你將上述代碼塊保存在 Medusa.py 中, 使用如下方式執行, 那麼你的設置可能有效:

python3 Medusa.py
複製代碼

你能夠自由配置你須要附加的屬性:code

  • 文本內容顏色
    • grey
    • red
    • green
    • yellow
    • blue
    • magenta
    • cyan
    • white
  • 文本背景顏色
    • on_grey
    • on_red
    • on_green
    • on_yellow
    • on_blue
    • on_magenta
    • on_cyan
    • on_white
  • 特殊屬性
    • bold
    • dark
    • underline
    • blink
    • reverse
    • concealed

在上述截圖中是否是參數沒有獲得生效呢?cdn

#!/usr/bin/env python
# _*_ Coding: UTF-8 _*_
from termcolor import cprint

cprint('color', 'green')
cprint('Medusa', color='red', on_color='on_yellow')
cprint('Sorcerer', attrs=['underline'])
複製代碼

實際上是模塊對 console 的兼容性問題, 期待它之後更新後更加兼容吧~
相關文章
相關標籤/搜索