7

Colored Output in Console with Python

 3 years ago
source link: https://blog.mathieu-leplatre.info/colored-output-in-console-with-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Colored Output in Console with Python

Colored Output in Console with Python

Wed 31 December 2008

Playing around with ANSI in a color capable terminal.

#!/usr/bin/env python
import sys

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

#following from Python cookbook, #475186
def has_colours(stream):
    if not hasattr(stream, "isatty"):
        return False
    if not stream.isatty():
        return False # auto color only on TTYs
    try:
        import curses
        curses.setupterm()
        return curses.tigetnum("colors") > 2
    except:
        # guess false in case of error
        return False
has_colours = has_colours(sys.stdout)


def printout(text, colour=WHITE):
        if has_colours:
                seq = "\x1b[1;%dm" % (30+colour) + text + "\x1b[0m"
                sys.stdout.write(seq)
        else:
                sys.stdout.write(text)

A simple demo:

<code python>
#
# Test
#
printout("[debug]   ", GREEN)
print("in green")
printout("[warning] ", YELLOW)
print("in yellow")
printout("[error]   ", RED)
print("in red")
ansi-color.png

#terminal, #python - Posted in the Dev category


© Copyright 2020 by Mathieu Leplatre. mnmlist Theme

Content licensed under the Creative Commons attribution-noncommercial-sharealike License.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK