python set text output color

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Time: 2018/5/5 20:43   
@Author: Jun Hong
"""

# Format: \033[display mode; foreground color; background color m
# illustrate:
#
# Foreground color background color
#   ---------------------------------------
# 30 40 Black
# 31 41 red
# 32 42 Green
# 33 43 Yellow
# 34 44 blue
# 35 45 Fuchsia
# 36 46 Turquoise
# 37 47 White
#
# Display meaning
#   -------------------------
# 0 Terminal default settings
# 1 Highlight
# 4 Use underscore
# 5 blink
# 7 Inverted
# 8 Invisible
#
# example:
# \033[1;31;40m <!--1-highlight 31-foreground red 40-background black-->
# \033[0m <!--Use the terminal default settings, that is, cancel the color settings-->]]]


STYLE = {
    'fore': { # Foreground color
        'black': 30,
        'red': 31,
        'green': 32,
        'yellow': 33,
        'blue': 34,
        'purple': 35, # purple
        'cyan': 36, # cyan blue
        'white': 37
    },
    'back': {# background color
        'black': 40,
        'red': 41,
        'green': 42,
        'yellow': 43,
        'blue': 44,
        'purple': 45,
        'cyan': 46,
        'white': 47,
    },
    'mode': { # display mode
        'mormal': 0, # Terminal default settings
        'bold': 1, # highlight
        'underline': 4, # use underscore
        'blink': 5, # blink
        'invert': 7, # invert
        'hide': 8 # invisible
    },
    'default': {'end': 0}
}


def UseStyle(string, mode='', fore='', back=''):
    mode = '%s' % STYLE['mode'][mode] if STYLE['mode'].__contains__(mode) else ''
    fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].__contains__(fore) else ''
    back = '%s' % STYLE['back'][back] if STYLE['back'].__contains__(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)


# Usage examples are as follows:
print(UseStyle('here is the information to be output', fore='red', mode='underline', back='blue'))

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325317021&siteId=291194637