True if stream supports colours. Python cookbook, #475186
184971
def stream_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:
        return False
649957
def color_print(s, color=None, highlight=None, end='\n', file=sys.stdout,
                **kwargs):
    
    if color in palette and color != 'default':
        s = palette[color] + s
    # Highlight / Background color.
    if highlight and highlight in highlighter:
        s = highlighter[highlight] + s
    # Custom string format.
    for name, value in kwargs.items():
        if name in formatter and value == True:
            s = formatter[name] + s
    print(s + palette['default'], end=end, file=file)
1297016
def bgwhite(cls, string, auto=False):
        
        return cls.colorize('bgwhite', string, auto=auto)
474550
def _get_colors(self):
        """"""
        try:
            csbi = _WindowsCSBI.get_info(self.win32_stream_handle)
            return csbi['fg_color'], csbi['bg_color']
        except IOError:
            return 7, 0
287657
def colors(self):
        """"""
        try:
            return get_console_info(self._kernel32, self._stream_handle)[:2]
        except OSError:
            return WINDOWS_CODES['white'], WINDOWS_CODES['black']
1266298
def is_output(self, stream):
        

        for streamer in self.streamers:
            if streamer.selector.matches(stream):
                return True

        return False
233769
def :
    
    # All argument types must be str.
    rtext = [str(f) for f in text]

    return COLORIZE_FORMAT.format(
        _to_int(bg), _to_int(base), _to_int(fg), ''.join(rtext)
    )
195047
public static function isColorsSupported($stream = STDOUT): bool
    {
        if ('Hyper' === getenv('TERM_PROGRAM')) {
            return true;
        }

        try {
            if (\DIRECTORY_SEPARATOR === '\\') {
                return (
                        function_exists('sapi_windows_vt100_support')
                        && @sapi_windows_vt100_support($stream)
                    ) || getenv('ANSICON') !== false
                    || getenv('ConEmuANSI') == 'ON'
                    || getenv('TERM') == 'xterm';
            }

            if (\function_exists('stream_isatty')) {
                return @stream_isatty($stream);
            }

            if (\function_exists('posix_isatty')) {
                return @posix_isatty($stream);
            }

            $stat = @fstat($stream);

            // Check if formatted mode is S_IFCHR
            return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
        } catch (\Throwable $e) {
            return false;
        }
    }
1006860
def _build_color_variants(cls):
    
    # Get the basic frame types first.
    frametypes = cls.sets(registered=False)

    _colornames = [
        # 'black', disabled for now, it won't show on my terminal.
        'red',
        'green',
        'yellow',
        'blue',
        'magenta',
        'cyan',
        'white',
    ]
    _colornames.extend('light{}'.format(s) for s in _colornames[:])
    for colorname in _colornames:
        for framesobj in frametypes:
            framename = '{}_{}'.format(framesobj.name, colorname)
            cls.register(
                framesobj.as_colr(fore=colorname),
                name=framename,
            )
36459
function _retrieveColor(palette, color, hue = '500', format) {
    if (typeof palette !== 'string' || typeof color !== 'string' || typeof hue !== 'string' || typeof format !== 'string') {
        throw new TypeError('Expected a string');
    }

    let hexColor;
    let result;

    try {
        hexColor = (palette === 'md') ? colors[palette][color][hue].hex : colors[palette][color];

        switch (format) {
            case 'rgb':
                result = _toRGB(hexColor);
                result = `rgb(${result.r}, ${result.g}, ${result.b})`;
                break;
            case 'hex':
                result = `#${hexColor}`;
                break;
            case 'raw':
                result = _toRGB(hexColor);
                result.hex = hexColor;
                break;
            default:
        }
    } catch (err) {
        throw new RangeError('No matching color.');
    }
    return result;
}
1306597
def check_color(c, greyscale, which):
    

    if c is None:
        return c
    if greyscale:
        try:
            len(c)
        except TypeError:
            c = (c,)
        if len(c) != 1:
            raise ProtocolError("%s for greyscale must be 1-tuple" % which)
        if not is_natural(c[0]):
            raise ProtocolError(
                "%s colour for greyscale must be integer" % which)
    else:
        if not (len(c) == 3 and
                is_natural(c[0]) and
                is_natural(c[1]) and
                is_natural(c[2])):
            raise ProtocolError(
                "%s colour must be a triple of integers" % which)
    return c
1336048
def colorize_logger(logger, stream=None, level=logging.DEBUG):
    
    logger.handlers = []
    logger.filters = []
    stream = stream or sys.stderr
    handler = logging.StreamHandler(stream=stream)
    handler.setLevel(level)
    handler.setFormatter(Colorful())
    logger.addHandler(handler)
    return logger
273951
def _print_stream_parameters(self, values):
        """"""
        cprint("{0}".format(*values), "magenta", attrs=["bold"])
        print("{4}".format(*values))
        cprint("  available formats:   {1}".format(*values), "blue")
        cprint("  mandatory selectors: {2}".format(*values), "red")
        cprint("  optional selectors:  {3}".format(*values), "green")
        print()
226096
def __stream_format_allowed(self, stream):
        
        # curses isn't available on all platforms
        try:
            import curses as CURSES
        except:
            return False
        try:
            CURSES.setupterm()
            return CURSES.tigetnum("colors") >= 2
        except:
            return False
543570
protected function hasColorSupport()
    {
        // @codeCoverageIgnoreStart
        if (DIRECTORY_SEPARATOR == '\\') {
            return false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI');
        }

        return function_exists('posix_isatty') && @posix_isatty($this->stream->stream);
        // @codeCoverageIgnoreEnd
    }
301180
def is_color(color):
    
    if not isinstance(color, basestring):
        return False
    elif RGB_HEX_REGEX.match(color):
        return True
    elif color in COLOR_ALIASES:
        return True
    elif color in cnames:
        return True
    return False
511972
def fprint(fmt, *args, **kwargs):
    
    if not fmt:
        return

    hascolor = False
    target = kwargs.get("target", sys.stdout)

    # Format the string before feeding it to the parser
    fmt = fmt.format(*args, **kwargs)

    for txt, markups in _color_format_parser.parse(fmt):
        if markups != (None, None):
            _color_manager.set_color(*markups)
            hascolor = True
        else:
            if hascolor:
                _color_manager.set_defaults()
                hascolor = False

        target.write(txt)
        target.flush()  # Needed for Python 3.x

    _color_manager.set_defaults()
    target.write(kwargs.get('end', '\n'))
    _color_manager.set_defaults()