import ctypes
# Constants from the Windows APISTD_OUTPUT_HANDLE = -11FOREGROUND_RED = 0x0004 # text color contains red.
def get_csbi_attributes(handle):# Based on IPython's winconsole.py, written by Alexander Belchenkoimport structcsbi = ctypes.create_string_buffer(22)res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)assert res
(bufx, bufy, curx, cury, wattr,left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)return wattr
handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)reset = get_csbi_attributes(handle)
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)print "Cherry on top"ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)
from icolor import cformat # there is also cprint
cformat("This is #RED;a red string, partially with a #xBLUE;blue background")'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'
# Display text on a Windows console# Windows XP with Python 2.7 or Python 3.2from ctypes import windll
# Needed for Python2/Python3 difftry:input = raw_inputexcept:passSTD_OUTPUT_HANDLE = -11stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)# Look at the output and select the color you want.# For instance, hex E is yellow on black.# Hex 1E is yellow on blue.# Hex 2E is yellow on green and so on.for color in range(0, 75):windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)print("%X --> %s" % (color, "Have a fine day!"))input("Press Enter to go on ... ")
""".. versionadded:: 0.9.2
Functions for wrapping strings in ANSI color codes.
Each function within this module returns the input string ``text``, wrappedwith ANSI color codes for the appropriate color.
For example, to print some text as green on supporting terminals::
from fabric.colors import green
print(green("This text is green!"))
Because these functions simply return modified strings, you can nest them::
from fabric.colors import red, green
print(red("This sentence is red, except for " + \green("these words, which are green") + "."))
If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped onfor that particular invocation, which usually shows up as a bold or brighterversion of the original color on most terminals."""
def _wrap_with(code):
def inner(text, bold=False):c = codeif bold:c = "1;%s" % creturn "\033[%sm%s\033[0m" % (c, text)return inner
red = _wrap_with('31')green = _wrap_with('32')yellow = _wrap_with('33')blue = _wrap_with('34')magenta = _wrap_with('35')cyan = _wrap_with('36')white = _wrap_with('37')
class colors:'''Colors class:Reset all colors with colors.resetTwo subclasses fg for foreground and bg for background.Use as colors.subclass.colorname.i.e. colors.fg.red or colors.bg.greenAlso, the generic bold, disable, underline, reverse, strikethrough,and invisible work with the main classi.e. colors.bold'''reset='\033[0m'bold='\033[01m'disable='\033[02m'underline='\033[04m'reverse='\033[07m'strikethrough='\033[09m'invisible='\033[08m'class fg:black='\033[30m'red='\033[31m'green='\033[32m'orange='\033[33m'blue='\033[34m'purple='\033[35m'cyan='\033[36m'lightgrey='\033[37m'darkgrey='\033[90m'lightred='\033[91m'lightgreen='\033[92m'yellow='\033[93m'lightblue='\033[94m'pink='\033[95m'lightcyan='\033[96m'class bg:black='\033[40m'red='\033[41m'green='\033[42m'orange='\033[43m'blue='\033[44m'purple='\033[45m'cyan='\033[46m'lightgrey='\033[47m'
from colorit import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces# Note: This clears the terminalinit_colorit()
# Foregroundprint(color("This text is red", Colors.red))print(color("This text is orange", Colors.orange))print(color("This text is yellow", Colors.yellow))print(color("This text is green", Colors.green))print(color("This text is blue", Colors.blue))print(color("This text is purple", Colors.purple))print(color("This text is white", Colors.white))
# Backgroundprint(background("This text has a background that is red", Colors.red))print(background("This text has a background that is orange", Colors.orange))print(background("This text has a background that is yellow", Colors.yellow))print(background("This text has a background that is green", Colors.green))print(background("This text has a background that is blue", Colors.blue))print(background("This text has a background that is purple", Colors.purple))print(background("This text has a background that is white", Colors.white))
# Customprint(color("This color has a custom grey text color", (150, 150, 150)))print(background("This color has a custom grey background", (150, 150, 150)))
# Combinationprint(background(color("This text is blue with a white background", Colors.blue), Colors.white))
# If you are using Windows Command Line, this is so that it doesn't close immediatelyinput()
def print_in_color(txt_msg, fore_tuple, back_tuple, ):# Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple# text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)rf,bf,gf = fore_tuplerb,gb,bb = back_tuplemsg = '{0}' + txt_msgmat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'print(msg .format(mat))print('\33[0m') # Returns default print color to back to black
# Example of use using a message with variablesfore_color = 'cyan'back_color = 'dark green'msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)print_in_color(msg, (0,255,255), (0,127,127))
from printy import printy
# With global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole textprinty("Hello, World!", "rBU")
# With inline formats, this will apply a dim (D)#blue (b) to the word 'Hello' and a stroken (S)#yellow (y) to the word 'world', and the rest will remain as the predefined formatprinty("this is a [bD]Hello@ [yS]world@ text")
# cprint is something like below# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)
# from console_color import RGB, Fore, Style, cprint, create_printfrom console_color import *
cprint("Hello, World!", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)cprint("Hello, World!", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)
📕: error message📙: warning message📗: ok status message📘: action message📓: canceled status message📔: Or anything you like and want to recognize immediately by color
import randomimport re as regexfrom rich import colorfrom rich import print
def create_dynamic_regex(search_words):"""This function is used to create a dynamic regular expressionstring and a list of random colors. Both these elements willbe used in the function colorize_text()
:param search_words: list of search terms:return: regular expression search string and a list of colors:rtype: string, list"""colors_required = create_list_of_colors(len(search_words))number_of_search_words = len(search_words)combined_string = ''for search_word in search_words:number_of_search_words -= 1if number_of_search_words != 0:current_string = ''.join(r'(\b' + search_word + r'\b)|')combined_string = (combined_string + current_string)elif number_of_search_words == 0:current_string = ''.join(r'(\b' + search_word + r'\b)')combined_string = (combined_string + current_string)return combined_string, colors_required
def random_color():"""This function is used to create a random color using thePython package rich.:return: color name:rtype: string"""selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))return selected_color
def create_list_of_colors(number_of_colors):"""This function is used to generate a list of colors,which will be used in the function colorize_text():param number_of_colors::return: list of colors:rtype: list"""list_of_colors = [random_color() for _ in range(number_of_colors)]return list_of_colors
def colorize_text(text, regex_string, array_of_colors):"""This function is used to colorize specific words in a text string.:param text: text string potentially containing specific words to colorize.:param regex_string: regular expression search string:param array_of_colors: list of colors:return: colorized text:rtype: string"""available_colors = array_of_colorsword_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)i = 0output = ""for word in word_regex.finditer(text):get_color = available_colors[word.lastindex - 1]output += "".join([text[i:word.start()],"[%s]" % available_colors[word.lastindex - 1],text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])i = word.end()return ''.join([output, text[word.end():]])
def generate_console_output(text_to_search, words_to_find):"""This function is used generate colorized text that willbe outputting to the console.
:param text_to_search: text string potentially containing specific words to colorize.:param words_to_find: list of search terms.:return: A string containing colorized words.:rtype: string"""search_terms, colors = create_dynamic_regex(words_to_find)colorize_html = colorize_text(text_to_search, search_terms, colors)print(colorize_html)
text = "The dog chased the cat that was looking for the mouse that the dog was playing with."words = ['dog', 'cat', 'mouse']generate_console_output(text, words)
import loggingimport coloredlogs
coloredlogs.install() # install a handler on the root logger
logging.debug('message with level debug')logging.info('message with level info')logging.warning('message with level warning')logging.error('message with level error')logging.critical('message with level critical')
结果:
从消息级调试开始:
import loggingimport coloredlogs
coloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug
logging.debug('message with level debug')logging.info('message with level info')logging.warning('message with level warning')logging.error('message with level error')logging.critical('message with level critical')
结果:
从库中隐藏消息:
import loggingimport coloredlogs
logger = logging.getLogger(__name__) # get a specific logger objectcoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debugcoloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object
logging.debug('message with level debug')logging.info('message with level info')logging.warning('message with level warning')logging.error('message with level error')logging.critical('message with level critical')
结果:
格式化日志消息:
import loggingimport coloredlogs
logger = logging.getLogger(__name__) # get a specific logger objectcoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debugcoloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger objectcoloredlogs.install(level='DEBUG', logger=logger,fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s')
logging.debug('message with level debug')logging.info('message with level info')logging.warning('message with level warning')logging.error('message with level error')logging.critical('message with level critical')
import os
os.system('')
def RGB(red=None, green=None, blue=None,bg=False):
if(bg==False and red!=None and green!=None and blue!=None):
return f'\u001b[38;2;{red};{green};{blue}m'
elif(bg==True and red!=None and green!=None and blue!=None):
return f'\u001b[48;2;{red};{green};{blue}m'
elif(red==None and green==None and blue==None):
return '\u001b[0m'
import os
os.system('color')
COLOR = '\033[91m' # change it, according to the color need
END = '\033[0m'
print(COLOR + "Hello World" + END) #print a message
exit=input() #to avoid closing the terminal windows
import coloring
# Directly use print-like functions
coloring.print_red('Hello', 12)
coloring.print_green('Hey', end="", sep=";")
print()
# Get str as return
print(coloring.red('hello'))
# Use the generic colorize function
print(coloring.colorize("I'm red", "red")) # Using color names
print(coloring.colorize("I'm green", (0, 255, 0))) # Using RGB colors
print(coloring.colorize("I'm blue", "#0000ff")) # Using hex colors
# Or using styles (underline, bold, italic, ...)
print(coloring.colorize('Hello', 'red', s='ub')) # underline and bold