`

python 之 彩色打印

阅读更多

封装 python 的彩色打印

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
#other chose type
编码    颜色/动作
0       重新设置属性到缺省设置
1       设置粗体
2       设置一半亮度(模拟彩色显示器的颜色)
4       设置下划线(模拟彩色显示器的颜色)
5       设置闪烁
7       设置反向图象
22      设置一般密度
24      关闭下划线
25      关闭闪烁
27      关闭反向图象
30      设置黑色前景
31      设置红色前景
32      设置绿色前景
33      设置棕色前景
34      设置蓝色前景
35      设置紫色前景
36      设置青色前景
37      设置白色前景
38      在缺省的前景颜色上设置下划线
39      在缺省的前景颜色上关闭下划线
40      设置黑色背景
41      设置红色背景
42      设置绿色背景
43      设置棕色背景
44      设置蓝色背景
45      设置紫色背景
46      设置青色背景
47      设置白色背景
49      设置缺省黑色背景
'''

g_mapPrintColor = {
#default setting
    'NORMAL' : 0,

#font setting
    'FONT_BOLD' : 1,
    'FONT_UNDERLINE' : 4,
    'FONT_SHINE' : 5,

#foreground setting
    'FOREGROUND_BACK' : 30,
    'FOREGROUND_RED' : 31,
    'FOREGROUND_GREEN' : 32,
    'FOREGROUND_BROWN' : 33,
    'FOREGROUND_BLUE' : 34,
    'FOREGROUND_PUPLE' : 35,
    'FOREGROUND_CYAN_BLUE' : 36,
    'FOREGROUND_WHITE' : 37,
    'FOREGROUND_UNDERLINE_ON'  : 38,
    'FOREGROUND_UNDERLINE_OFF' : 39,

#background setting
    'BACKGROUND_BACK' : 40,
    'BACKGROUND_RED' : 41,
    'BACKGROUND_GREEN' : 42,
    'BACKGROUND_BROWN' : 43,
    'BACKGROUND_BLUE' : 44,
    'BACKGROUND_PUPLE' : 45,
    'BACKGROUND_CYAN_BLUE' : 46,
    'BACKGROUND_WHITE' : 47,
    'BACKGROUND_DEFAULT_BACK' : 49,
};

def GetColorPrintParam(strKey):
    nDefVal = g_mapPrintColor['NORMAL'];
    
    if not strKey:
        return nDefVal;
    
    if g_mapPrintColor.has_key(strKey):
        return g_mapPrintColor[strKey];
    
    return nDefVal;

def ColorPrint(strPrint, nFont = 0, clrFore = 0, clrBack = 0, bReturn = True):
    if not strPrint:
        return 0;
    
    strPrefix = "\033[%d;%d;%dm" %(nFont, clrFore, clrBack);
    strSuffix = "\033[0m";
    strMsg = strPrefix + strPrint + strSuffix;
    
    if bReturn:
        print(strMsg);
    else:
        print strMsg,;
        
    return len(strPrint);

#def ColorPrintLine(strPrint, nFont = 0, clrFore = 0, clrBack = 0, bReturn = True):
#    (nWidth, nHeight) = GetTerminalSize();
    
#    print("width:%d  ==> height:%d" %(nWidth, nHeight));
    
#    return ColorPrint(strPrint, nFont, clrFore, clrBack, bReturn);
    
    
    

 

调用部分:

#!/usr/bin/env python
import ColorPrint;

if "__main__" == __name__:
    
    strPrint = "hello, andylin!";
    nFont = ColorPrint.GetColorPrintParam('FONT_SHINE');
    clrFore = ColorPrint.GetColorPrintParam('FOREGROUND_RED');
    clrBack = ColorPrint.GetColorPrintParam('BACKGROUND_WHITE');
    
    ColorPrint.ColorPrint(strPrint,nFont, clrFore, clrBack, True);
    
    print("ok");
    
    #ColorPrint.ColorPrintLine(strPrint,nFont, clrFore, clrBack, True);
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics