Python实现设置终端显示颜色、粗体、下划线等效果

也许你希望在终端上输出一些带有颜色或者粗体、下划线等样式的信息,就像man中的那样,那么这篇文章将会起到些许作用。

事件起因


在Python开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中。

但是很杂乱的信息显示在一起,往往没有重点,一个一个找我们需要的信息往往特别复杂.

杂乱无章的信息

Linux下的终端设置


linux终端颜色设置信息


在Linux终端中,使用转义序列来进行如上所述的显示,转义序列以ESC开头,即ASCII码下的\033,其格式为:

\033[显示方式;前景色;背景色m

显示方式、前景色、背景色至少一个存在即可。
格式:\033[显示方式;前景色;背景色m

说明


前景色背景色颜色
3040黑色
3141红色
3242绿色
3343黃色
3444蓝色
3545紫红色
3646青蓝色
3747白色

显示方式


显示方式意义
0终端默认设置
1高亮显示
4使用下划线
5闪烁
7反白显示
8不可见

例子


\033[1;31;40m    <!--1-高亮显示 31-前景色红色  40-背景色黑色-->
\033[0m          <!--采用终端默认设置,即取消颜色设置-->

Linux下解决

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


#   格式:\033[显示方式;前景色;背景色m
#   说明:
#
#   前景色            背景色            颜色
#   ---------------------------------------
#     30                40              黑色
#     31                41              红色
#     32                42              绿色
#     33                43              黃色
#     34                44              蓝色
#     35                45              紫红色
#     36                46              青蓝色
#     37                47              白色
#
#   显示方式           意义
#   -------------------------
#      0           终端默认设置
#      1             高亮显示
#      4            使用下划线
#      5              闪烁
#      7             反白显示
#      8              不可见
#
#   例子:
#   \033[1;31;40m    <!--1-高亮显示 31-前景色红色  40-背景色黑色-->
#   \033[0m          <!--采用终端默认设置,即取消颜色设置-->]]]


STYLE = {
        'fore':
        {   # 前景色
            'black'    : 30,   #  黑色
            'red'      : 31,   #  红色
            'green'    : 32,   #  绿色
            'yellow'   : 33,   #  黄色
            'blue'     : 34,   #  蓝色
            'purple'   : 35,   #  紫红色
            'cyan'     : 36,   #  青蓝色
            'white'    : 37,   #  白色
        },

        'back' :
        {   # 背景
            'black'     : 40,  #  黑色
            'red'       : 41,  #  红色
            'green'     : 42,  #  绿色
            'yellow'    : 43,  #  黄色
            'blue'      : 44,  #  蓝色
            'purple'    : 45,  #  紫红色
            'cyan'      : 46,  #  青蓝色
            'white'     : 47,  #  白色
        },

        'mode' :
        {   # 显示模式
            'mormal'    : 0,   #  终端默认设置
            'bold'      : 1,   #  高亮显示
            'underline' : 4,   #  使用下划线
            'blink'     : 5,   #  闪烁
            'invert'    : 7,   #  反白显示
            'hide'      : 8,   #  不可见
        },

        'default' :
        {
            'end' : 0,
        },
}


def UseStyle(string, mode = '', fore = '', back = ''):

    mode  = '%s' % STYLE['mode'][mode] if STYLE['mode'].has_key(mode) else ''

    fore  = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else ''

    back  = '%s' % STYLE['back'][back] if STYLE['back'].has_key(back) else ''

    style = ';'.join([s for s in [mode, fore, back] if s])

    style = '\033[%sm' % style if style else ''

    end   = '\033[%sm' % STYLE['default']['end'] if style else ''

    return '%s%s%s' % (style, string, end)



def TestColor( ):

    print UseStyle('正常显示')
    print ''

    print "测试显示模式"
    print UseStyle('高亮',   mode = 'bold'),
    print UseStyle('下划线', mode = 'underline'),
    print UseStyle('闪烁',   mode = 'blink'),
    print UseStyle('反白',   mode = 'invert'),
    print UseStyle('不可见', mode = 'hide')
    print ''


    print "测试前景色"
    print UseStyle('黑色',   fore = 'black'),
    print UseStyle('红色',   fore = 'red'),
    print UseStyle('绿色',   fore = 'green'),
    print UseStyle('黄色',   fore = 'yellow'),
    print UseStyle('蓝色',   fore = 'blue'),
    print UseStyle('紫红色', fore = 'purple'),
    print UseStyle('青蓝色', fore = 'cyan'),
    print UseStyle('白色',   fore = 'white')
    print ''


    print "测试背景色"
    print UseStyle('黑色',   back = 'black'),
    print UseStyle('红色',   back = 'red'),
    print UseStyle('绿色',   back = 'green'),
    print UseStyle('黄色',   back = 'yellow'),
    print UseStyle('蓝色',   back = 'blue'),
    print UseStyle('紫红色', back = 'purple'),
    print UseStyle('青蓝色', back = 'cyan'),
    print UseStyle('白色',   back = 'white')
    print ''
if __name__ == '__main__':

    TestColor( )

终端颜色设置

附上用于测试的Linux下C程序

/**********************************************************
    > File Name: test.c
    > Author: GatieMe
    > Mail: gatieme@163.com
    > Created Time: 2015年04月26日 星期日 11时03分48秒
 *********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 *
 *    格式:\033[显示方式;前景色;背景色m
 *    说明:
 *
 *    前景色            背景色            颜色
 *    ---------------------------------------
 *      30                40              黑色
 *      31                41              红色
 *      32                42              绿色
 *      33                43              黃色
 *      34                44              蓝色
 *      35                45              紫红色
 *      36                46              青蓝色
 *      37                47              白色
 *
 *    显示方式           意义
 *    -------------------------
 *       0           终端默认设置
 *       1             高亮显示
 *       4            使用下划线
 *       5              闪烁
 *       7             反白显示
 *       8              不可见
 *
 *    例子:
 *    \033[1;31;40m    <!--1-高亮显示 31-前景色红色  40-背景色黑色-->
 *    \033[0m          <!--采用终端默认设置,即取消颜色设置-->
 **/



int main(void)
{
    int left, right;

    while(printf("\033[31m"),  /*  输入数据红色显示  */
          scanf("%d%d", &left, &right) != EOF)
    {
        printf("\033[1;32m%d\033[0m\n", left + right);  /* 输出信息绿色高亮显示  */

    }

    return  EXIT_SUCCESS;
}

window下终端颜色显示


终端I/O库WConio

项目地址:http://newcenturycomputers.net/projects/wconio.html

在linux系统中,终端内可以通过curse模块或控制字符来输出彩色文本,但是在windows系统中没有curse模块也不能用控制字符,只能调用win32console模块中的控制台相关函数。直接调用这些函数还是比较麻烦的,因此有人弄了个WConio模块,封装了这些函数的功能。使用WConio,彩色文本的输出变得简单:

import WConio
attr=WConio.gettextinfo()[4] #保存默认文本颜色
WConio.textcolor(WConio.RED) #将后续输出的文本的颜色设为红色
print "红色的文字"
WConio.settextattr(attr) #回复默认的文本颜色

调用底层C库


该代码片段来自于: http://www.sharejs.com/codes/python/8665

#!/usr/bin/env python 
#encoding: utf-8
import ctypes

STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12

FOREGROUND_BLACK = 0x0
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color is intensified.

BACKGROUND_BLUE = 0x10 # background color contains blue.
BACKGROUND_GREEN= 0x20 # background color contains green.
BACKGROUND_RED = 0x40 # background color contains red.
BACKGROUND_INTENSITY = 0x80 # background color is intensified.

class Color:
    ''' See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winprog/winprog/windows_api_reference.asp
    for information on Windows APIs. - www.sharejs.com'''
    std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

    def set_cmd_color(self, color, handle=std_out_handle):
        """(color) -> bit
        Example: set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
        """
        bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
        return bool

    def reset_color(self):
        self.set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)

    def print_red_text(self, print_text):
        self.set_cmd_color(FOREGROUND_RED | FOREGROUND_INTENSITY)
        print print_text
        self.reset_color()

    def print_green_text(self, print_text):
        self.set_cmd_color(FOREGROUND_GREEN | FOREGROUND_INTENSITY)
        print print_text
        self.reset_color()

    def print_blue_text(self, print_text):
        self.set_cmd_color(FOREGROUND_BLUE | FOREGROUND_INTENSITY)
        print print_text
        self.reset_color()

    def print_red_text_with_blue_bg(self, print_text):
        self.set_cmd_color(FOREGROUND_RED | FOREGROUND_INTENSITY| BACKGROUND_BLUE | BACKGROUND_INTENSITY)
        print print_text
        self.reset_color()   

if __name__ == "__main__":
    clr = Color()
    clr.print_red_text('red')
    clr.print_green_text('green')
    clr.print_blue_text('blue')
    clr.print_red_text_with_blue_bg('background')

调用底层C库

跨平台解决方案colorama


项目地址https://pypi.python.org/pypi/colorama
colorama

示例


#!/usr/bin/env python 
#encoding: utf-8

from colorama import init, Fore, Back, Style


if __name__ == "__main__":

    init(autoreset=True)    #  初始化,并且设置颜色设置自动恢复
    print(Fore.RED + 'some red text')
    print(Back.GREEN + 'and with a green background')
    print(Style.DIM + 'and in dim text')
    # 如果未设置autoreset=True,需要使用如下代码重置终端颜色为初始设置
    #print(Fore.RESET + Back.RESET + Style.RESET_ALL)  autoreset=True
    print('back to normal now')

安装


使用pip安装

pip install colorama 

下载源码安装, 然后打开cmd进入源码目录

python setup.py build
python setup.py install
  • 15
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值