写了个支持Linux下变换字体颜色的module,highlight方法是为了改变成需要的颜色之后还能改回到原来的颜色,否则Linux会一直持续使用改变的颜色。

#!/usr/bin/env python
def inBlack(s):
    return highlight('') + "%s[30;2m%s%s[0m"%(chr(27), s, chr(27))

def inRed(s):
    return highlight('') + "%s[31;2m%s%s[0m"%(chr(27), s, chr(27))

def inGreen(s):
    return highlight('') + "%s[32;2m%s%s[0m"%(chr(27), s, chr(27))

def inYellow(s):
    return highlight('') + "%s[33;2m%s%s[0m"%(chr(27), s, chr(27))

def inBlue(s):
    return highlight('') + "%s[34;2m%s%s[0m"%(chr(27), s, chr(27))

def inPurple(s):
    return highlight('') + "%s[35;2m%s%s[0m"%(chr(27), s, chr(27))

def inWhite(s):
    return highlight('') + "%s[37;2m%s%s[0m"%(chr(27), s, chr(27))

def highlight(s):
    return "%s[30;2m%s%s[1m"%(chr(27), s, chr(27))

#print inPurple('You got ') + inGreen('nothingtototototototototo') + ' to say,' + ' Keep comments to ' + inYellow('yourself') + ' , lately, i have got a ' + inRed('problem') + ' with the way that you behave'


使用前先import,然后就可以直接调用了:

from color import inRed,inGreen,inPurple,inYellow
def test():
        print inGreen("pass")
        print inRed("fail\n")
        print inPurple("`````````````````````````````")
        print inPurple('You got ') + inGreen('nothingtototototototototo') + ' to say,' + ' Keep comments to ' + inYellow('yourself') + ' , lately, i have got a ' + inRed('problem') + ' with the way that you behave'
test()

打印结果:

Python_Linux文字变换颜色_shell