How to print colored text in Python?

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

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

30条回答
  •  春和景丽
    2020-11-21 05:25

    I know that I am late. But, I have a library called colorit. It is super simple.

    Here are some examples:

    from colorit import *
    
    # Use this to ensure that ColorIt will be usable by certain command line interfaces
    # Note: This clears the terminal
    init_colorit()
    
    # Foreground
    print(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))
    
    # Background
    print(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))
    
    # Custom
    print(color("This color has a custom grey text color", (150, 150, 150)))
    print(background("This color has a custom grey background", (150, 150, 150)))
    
    # Combination
    print(
        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 immediately
    input()
    

    This gives you:

    It's also worth noting that this is cross platform and has been tested on mac, linux, and windows.

    You might want to try it out: https://github.com/SuperMaZingCoder/colorit

    Edit: colorit is now available to be installed with PyPi! You can install it with pip install color-it on Windows and pip3 install color-it on macOS and Linux.

提交回复
热议问题