python 自訂linux控制台輸出

來源:互聯網
上載者:User

如何向控制台輸出彩色列印資訊呢?如何訂製自己的輸出格式呢?下面將告訴你……

import os

"""
0 All attributes off 預設值
1 Bold (or Bright) 粗體 or 高亮
4 Underline 底線
5 Blink 閃爍
7 Reverse 反顯
30 Black text
31 Red text
32 Green text
33 Yellow text
34 Blue text
35 Purple text
36 Cyan text
37 White text
40 Black background
41 Red background
42 Green background
43 Yellow background
44 Blue background
45 Purple background
46 Cyan background
47 White background
"""

def colored(text, color=None, on_color=None, attrs=None):
fmt_str = '\x1B[;%dm%s\x1B[0m'
if color is not None:
text = fmt_str % (color, text)

if on_color is not None:
text = fmt_str % (on_color, text)

if attrs is not None:
for attr in attrs:
text = fmt_str % (color, text)

return text

def printError(msg):
print colored(msg, color=31)

def printWarning(msg):
print colored(msg, color=33)

def printInfo(msg):
print colored(msg, color=37)

if __name__ == '__main__':
printError("this is an error message!")
printWarning("this is a warning message!")
printInfo("this ia a info message!")

輸出:

參考:
http://www.oschina.net/code/snippet_87675_8599
http://pypi.python.org/pypi/termcolor/0.1.1#downloads

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.