How to print colored text in Python?

前端 未结 30 2912
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

相关标签:
30条回答
  • 2020-11-21 05:12

    I'm surprised no one has mentioned the Python termcolor module. Usage is pretty simple:

    from termcolor import colored
    
    print colored('hello', 'red'), colored('world', 'green')
    

    Or in Python 3:

    print(colored('hello', 'red'), colored('world', 'green'))
    

    It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...

    0 讨论(0)
  • 2020-11-21 05:12

    You want to learn about ANSI escape sequences. Here's a brief example:

    CSI="\x1B["
    print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
    

    For more info see http://en.wikipedia.org/wiki/ANSI_escape_code

    For a block character, try a unicode character like \u2588:

    print(u"\u2588")
    

    Putting it all together:

    print(CSI+"31;40m" + u"\u2588" + CSI + "0m")
    
    0 讨论(0)
  • 2020-11-21 05:12

    generated a class with all the colors using a for loop to iterate every combination of color up to 100, then wrote a class with python colors. Copy and paste as you will, GPLv2 by me:

    class colors:
        '''Colors class:
        reset all colors with colors.reset
        two subclasses fg for foreground and bg for background.
        use as colors.subclass.colorname.
        i.e. colors.fg.red or colors.bg.green
        also, the generic bold, disable, underline, reverse, strikethrough,
        and invisible work with the main class
        i.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'
    
    0 讨论(0)
  • 2020-11-21 05:12

    Building on @joeld answer, using https://pypi.python.org/pypi/lazyme pip install -U lazyme :

    from lazyme.string import color_print
    >>> color_print('abc')
    abc
    >>> color_print('abc', color='pink')
    abc
    >>> color_print('abc', color='red')
    abc
    >>> color_print('abc', color='yellow')
    abc
    >>> color_print('abc', color='green')
    abc
    >>> color_print('abc', color='blue', underline=True)
    abc
    >>> color_print('abc', color='blue', underline=True, bold=True)
    abc
    >>> color_print('abc', color='pink', underline=True, bold=True)
    abc
    

    Screenshot:


    Some updates to the color_print with new formatters, e.g.:

    >>> from lazyme.string import palette, highlighter, formatter
    >>> from lazyme.string import color_print
    >>> palette.keys() # Available colors.
    ['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
    >>> highlighter.keys() # Available highlights.
    ['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
    >>> formatter.keys() # Available formatter, 
    ['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
    

    Note: italic, fast blinking and strikethrough may not work on all terminals, doesn't work on Mac / Ubuntu.

    E.g.

    >>> color_print('foo bar', color='pink', highlight='white')
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', reverse=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', bold=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', faint=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
    foo bar
    

    Screenshot:

    0 讨论(0)
  • 2020-11-21 05:12

    asciimatics provides a portable support for building text UI and animations:

    #!/usr/bin/env python
    from asciimatics.effects import RandomNoise  # $ pip install asciimatics
    from asciimatics.renderers import SpeechBubble, Rainbow
    from asciimatics.scene import Scene
    from asciimatics.screen import Screen
    from asciimatics.exceptions import ResizeScreenError
    
    
    def demo(screen):
        render = Rainbow(screen, SpeechBubble('Rainbow'))
        effects = [RandomNoise(screen, signal=render)]
        screen.play([Scene(effects, -1)], stop_on_resize=True)
    
    while True:
        try:
            Screen.wrapper(demo)
            break
        except ResizeScreenError:
            pass
    

    Asciicast:

    0 讨论(0)
  • 2020-11-21 05:13

    Define a string that starts a color and a string that ends the color, then print your text with the start string at the front and the end string at the end.

    CRED = '\033[91m'
    CEND = '\033[0m'
    print(CRED + "Error, does not compute!" + CEND)
    

    This produces the following in bash, in urxvt with a Zenburn-style color scheme:

    Through experimentation, we can get more colors:

    Note: \33[5m and \33[6m are blinking.

    This way we can create a full color collection:

    CEND      = '\33[0m'
    CBOLD     = '\33[1m'
    CITALIC   = '\33[3m'
    CURL      = '\33[4m'
    CBLINK    = '\33[5m'
    CBLINK2   = '\33[6m'
    CSELECTED = '\33[7m'
    
    CBLACK  = '\33[30m'
    CRED    = '\33[31m'
    CGREEN  = '\33[32m'
    CYELLOW = '\33[33m'
    CBLUE   = '\33[34m'
    CVIOLET = '\33[35m'
    CBEIGE  = '\33[36m'
    CWHITE  = '\33[37m'
    
    CBLACKBG  = '\33[40m'
    CREDBG    = '\33[41m'
    CGREENBG  = '\33[42m'
    CYELLOWBG = '\33[43m'
    CBLUEBG   = '\33[44m'
    CVIOLETBG = '\33[45m'
    CBEIGEBG  = '\33[46m'
    CWHITEBG  = '\33[47m'
    
    CGREY    = '\33[90m'
    CRED2    = '\33[91m'
    CGREEN2  = '\33[92m'
    CYELLOW2 = '\33[93m'
    CBLUE2   = '\33[94m'
    CVIOLET2 = '\33[95m'
    CBEIGE2  = '\33[96m'
    CWHITE2  = '\33[97m'
    
    CGREYBG    = '\33[100m'
    CREDBG2    = '\33[101m'
    CGREENBG2  = '\33[102m'
    CYELLOWBG2 = '\33[103m'
    CBLUEBG2   = '\33[104m'
    CVIOLETBG2 = '\33[105m'
    CBEIGEBG2  = '\33[106m'
    CWHITEBG2  = '\33[107m'
    

    Here is the code to generate the test:

    x = 0
    for i in range(24):
      colors = ""
      for j in range(5):
        code = str(x+j)
        colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
      print(colors)
      x=x+5
    
    0 讨论(0)
提交回复
热议问题