How to print colored text in Python?

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

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

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

    On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.

    To see complete code that supports both ways, see the color console reporting code from Testoob.

    ctypes example:

    import ctypes
    
    # Constants from the Windows API
    STD_OUTPUT_HANDLE = -11
    FOREGROUND_RED    = 0x0004 # text color contains red.
    
    def get_csbi_attributes(handle):
        # Based on IPython's winconsole.py, written by Alexander Belchenko
        import struct
        csbi = 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)
    
    0 讨论(0)
  • 2020-11-21 05:05

    https://raw.github.com/fabric/fabric/master/fabric/colors.py

    """
    .. versionadded:: 0.9.2
    
    Functions for wrapping strings in ANSI color codes.
    
    Each function within this module returns the input string ``text``, wrapped
    with 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 on
    for that particular invocation, which usually shows up as a bold or brighter
    version of the original color on most terminals.
    """
    
    
    def _wrap_with(code):
    
        def inner(text, bold=False):
            c = code
            if bold:
                c = "1;%s" % c
            return "\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')
    
    0 讨论(0)
  • 2020-11-21 05:07

    Stupidly simple based on @joeld's answer

    class PrintInColor:
        RED = '\033[91m'
        GREEN = '\033[92m'
        YELLOW = '\033[93m'
        LIGHT_PURPLE = '\033[94m'
        PURPLE = '\033[95m'
        END = '\033[0m'
    
        @classmethod
        def red(cls, s, **kwargs):
            print(cls.RED + s + cls.END, **kwargs)
    
        @classmethod
        def green(cls, s, **kwargs):
            print(cls.GREEN + s + cls.END, **kwargs)
    
        @classmethod
        def yellow(cls, s, **kwargs):
            print(cls.YELLOW + s + cls.END, **kwargs)
    
        @classmethod
        def lightPurple(cls, s, **kwargs):
            print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
    
        @classmethod
        def purple(cls, s, **kwargs):
            print(cls.PURPLE + s + cls.END, **kwargs)
    

    Then just

    PrintInColor.red('hello', end=' ')
    PrintInColor.green('world')
    
    0 讨论(0)
  • 2020-11-21 05:10

    I'm responding because I have found out a way to use ANSI codes on Windows 10, so that you can change the colour of text without any modules that aren't built in:

    The line that makes this work is os.system(""), or any other system call, which allows you to print ANSI codes in the Terminal:

    import os
    
    os.system("")
    
    # Group of Different functions for different styles
    class style():
        BLACK = '\033[30m'
        RED = '\033[31m'
        GREEN = '\033[32m'
        YELLOW = '\033[33m'
        BLUE = '\033[34m'
        MAGENTA = '\033[35m'
        CYAN = '\033[36m'
        WHITE = '\033[37m'
        UNDERLINE = '\033[4m'
        RESET = '\033[0m'
    
    print(style.YELLOW + "Hello, World!")
    

    Note: Although this gives the same options as other Windows options, Windows does not full support ANSI codes, even with this trick. Not all the text decoration colours work and all the 'bright' colours (Codes 90-97 and 100-107) display the same as the regular colours (Codes 30-37 and 40-47)

    Edit: Thanks to @j-l for finding an even shorter method.

    tl;dr: Add os.system("") near the top of your file.

    Python Version: 3.6.7

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

    YAY! another version

    while i find this answer useful, i modified it a bit. this Github Gist is the result

    usage

    print colors.draw("i'm yellow", bold=True, fg_yellow=True)
    

    enter image description here

    in addition you can wrap common usages:

    print colors.error('sorry, ')
    

    asd

    https://gist.github.com/Jossef/0ee20314577925b4027f

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

    You could use CLINT:

    from clint.textui import colored
    print colored.red('some warning message')
    print colored.green('nicely done!')
    

    Get it from GitHub.

    0 讨论(0)
提交回复
热议问题