How to print colored text in Python?

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

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

30条回答
  •  Happy的楠姐
    2020-11-21 05:21

    If you are using Windows, then here you go!

    # display text on a Windows console
    # Windows XP with Python27 or Python32
    from ctypes import windll
    # needed for Python2/Python3 diff
    try:
        input = raw_input
    except:
        pass
    STD_OUTPUT_HANDLE = -11
    stdout_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 ... ")
    

提交回复
热议问题