之前在 这里看到别人的实现。貌似已经不能访问了。一直使用这个实现很方便。最近发现有时候输出的内容跟原生的 print 方法输出的内容不一致,差异很大。于是就看了一下具体逻辑。发现这个实现把全部的参数转成字符串然后打印了。就是这个原因了,我就改了一下,然后现在就能跟 print 输出是完全一样的内容了。

核心代码很短:

def _color(*args, color='[0;', sep=' ', end='\n', file=None):
    """
    原来的实现在打印对象的时候,跟 print 输出的结果不一致。改成像现在这样就一致了。
    """
    if len(args) > 0:
        for obj in args[0:-1]:
            values = '\033{}{}\033[0m'.format(color, obj)
            print(values, sep=sep, end=sep, file=file)
        print('\033{}{}\033[0m'.format(color, args[-1]), sep=sep, end=end, file=file)
    else:
        print('\033{}{}\033[0m'.format(color, args[0]), sep=sep, end=end, file=file)

这样就能一致了,但是光看这个估计还是不知道怎么使用,因为不知道 color 应该给什么值进去。

关于 color 值,我就按照之前的博主的实现来的,没有去改动。颜色效果很好。

直接给出一个写好的类,方便大家使用。

完整实现:

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

"""

{ 开头部分:\033[显示方式;前景色;背景色m + 结尾部分:\033[0m  }
注意:开头部分的三个参数:显示方式,前景色,背景色是可选参数,可以只写其中的某一个;
另外由于表示三个参数不同含义的数值都是唯一的没有重复的,所以三个参数的书写先后顺序没有固定要求,系统都能识别;但是,建议按照默认的格式规范书写。
对于结尾部分,其实也可以省略,但是为了书写规范,建议\033[***开头,\033[0m结尾。

-------

数值表示的参数含义:
显示方式: 0(默认\)、1(高亮)、22(非粗体)、4(下划线)、24(非下划线)、 5(闪烁)、25(非闪烁)、7(反显)、27(非反显)
前景色:   30(黑色)、31(红色)、32(绿色)、 33(黄色)、34(蓝色)、35(洋 红)、36(青色)、37(白色)
背景色:   40(黑色)、41(红色)、42(绿色)、 43(黄色)、44(蓝色)、45(洋 红)、46(青色)、47(白色)
"""


def _color(*args, color='[0;', sep=' ', end='\n', file=None):
    """
    原来的实现在打印对象的时候,跟 print 输出的结果不一致。改成像现在这样就一致了。
    """
    if len(args) > 0:
        for obj in args[0:-1]:
            values = '\033{}{}\033[0m'.format(color, obj)
            print(values, sep=sep, end=sep, file=file)
        print('\033{}{}\033[0m'.format(color, args[-1]), sep=sep, end=end, file=file)
    else:
        print('\033{}{}\033[0m'.format(color, args[0]), sep=sep, end=end, file=file)


def green(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;32m', sep=sep, end=end, file=file)


def red(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;31m', sep=sep, end=end, file=file)


def yellow(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;33m', sep=sep, end=end, file=file)


def blue(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;34m', sep=sep, end=end, file=file)


def good(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;36m', sep=sep, end=end, file=file)


def white(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;37m', sep=sep, end=end, file=file)


def normal(*args, sep=' ', end='\n', file=None):
    _color(*args, color='[0;39m', sep=sep, end=end, file=file)


def black(*args, sep=' , ', end='\n', file=None):
    _color(*args, color='[0;30m', sep=sep, end=end, file=file)