How to print colored text in Python?

前端 未结 30 2973
谎友^
谎友^ 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)
    

提交回复
热议问题