Skip to content
holzkohlengrill edited this page Dec 15, 2023 · 2 revisions

Coloured std::out in python3

These examples are heavily based on SCout python library (MIT licenced; Copyright (c) 2017-2019 Marcel Schmalzl).

Check for colour support

Check whether std::out can use colour (optional)

import sys

def _canUseColour():
    """
    Checks if coloured text output is supported
    :return: True if colours are supported, otherwise False
    """
    supportedPlatforms = ["linux", "cygwin", "darwin"]
    platformSupported = False

    for platform in supportedPlatforms:
        if sys.platform.startswith(platform):
            platformSupported = True
            break

    isTty = hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty()
    if platformSupported or isTty:
        return True
    else:
        return False

Colour definitions

Some colour definitions

class Colours:
    """
    Colour definitions
    """
    WHITE = '\033[37m'          # Indeed very light grey
    LIGHT_CYAN = '\033[36m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    WARNING = '\033[93m'        # Yellow
    WWARNING = '\033[33m'       # Dark Grey
    ERROR = '\033[91m'          # Light red
    HEADER = '\033[1m'          # Bold white
    UNDERLINE = '\033[4m'

    NO_COLOUR = '\033[0m'       # Reset text colour

Use the above functions for coloured std::out

colour = ""
stdColour = ""
if _canUseColour():
    colour = Colours.WARNING
    stdColour = Colours.WHITE
textOut = " ".join([colour + text + stdColour])
print(textOut)
Clone this wiki locally