How to print colored text in Python?

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

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

相关标签:
30条回答
  • 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 ... ")
    
    0 讨论(0)
  • 2020-11-21 05:21

    If you are using Django

    >>> from django.utils.termcolors import colorize
    >>> print colorize("Hello World!", fg="blue", bg='red',
    ...                 opts=('bold', 'blink', 'underscore',))
    Hello World!
    >>> help(colorize)
    

    snapshot:

    image

    (I generally use colored output for debugging on runserver terminal so I added it.)

    You can test if it is installed in your machine:
    $ python -c "import django; print django.VERSION"
    To install it check: How to install Django

    Give it a Try!!

    0 讨论(0)
  • sty is similar to colorama, but it's less verbose, supports 8bit and 24bit (rgb) colors, allows you to register your own styles, supports muting, is really flexible, well documented and more.

    Examples:

    from sty import fg, bg, ef, rs
    
    foo = fg.red + 'This is red text!' + fg.rs
    bar = bg.blue + 'This has a blue background!' + bg.rs
    baz = ef.italic + 'This is italic text' + rs.italic
    qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
    qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
    
    # Add custom colors:
    
    from sty import Style, RgbFg
    
    fg.orange = Style(RgbFg(255, 150, 50))
    
    buf = fg.orange + 'Yay, Im orange.' + fg.rs
    
    print(foo, bar, baz, qux, qui, buf, sep='\n')
    

    prints:

    Demo:

    0 讨论(0)
  • 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.

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

    My favorite way is with the Blessings library (full disclosure: I wrote it). For example:

    from blessings import Terminal
    
    t = Terminal()
    print t.red('This is red.')
    print t.bold_bright_red_on_black('Bright red on black')
    

    To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:

    print t.on_green(' ')
    

    You can print in specific locations as well:

    with t.location(0, 5):
        print t.on_yellow(' ')
    

    If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:

    print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
    

    The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!

    0 讨论(0)
  • 2020-11-21 05:26
    def black(text):
        print('\033[30m', text, '\033[0m', sep='')
    
    def red(text):
        print('\033[31m', text, '\033[0m', sep='')
    
    def green(text):
        print('\033[32m', text, '\033[0m', sep='')
    
    def yellow(text):
        print('\033[33m', text, '\033[0m', sep='')
    
    def blue(text):
        print('\033[34m', text, '\033[0m', sep='')
    
    def magenta(text):
        print('\033[35m', text, '\033[0m', sep='')
    
    def cyan(text):
        print('\033[36m', text, '\033[0m', sep='')
    
    def gray(text):
        print('\033[90m', text, '\033[0m', sep='')
    
    
    black("BLACK")
    red("RED")
    green("GREEN")
    yellow("YELLOW")
    blue("BLACK")
    magenta("MAGENTA")
    cyan("CYAN")
    gray("GRAY")
    

    Try online

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