"""Checks if the current terminal supports colors. Also specifies the stream to write to. On Windows, this is a wrapped stream. """ import errno import os import struct import sys STREAM = sys.stderr SUPPORTS_COLOR = False def get_terminfo_file(): term = os.getenv('TERM', None) if term is None: return None terminfo_path = os.path.join('/usr/share/terminfo', ('%0.2X' % ord(term[0])), term) try: f = open(terminfo_path, 'rb') except IOError as e: if e.errno != errno.ENOENT: raise terminfo_path = os.path.join('/usr/share/terminfo', term[0], term) try: f = open(terminfo_path, 'rb') except IOError as e: if e.errno != errno.ENOENT: raise return None return f if os.name == 'nt': from colorama import init as init_colorama, AnsiToWin32 init_colorama(wrap=False) STREAM = AnsiToWin32(sys.stderr).stream SUPPORTS_COLOR = True else: if os.getenv('FORCE_COLOR', None) == '1': SUPPORTS_COLOR = True else: f = get_terminfo_file() if f is not None: with f: # f is a valid terminfo; seek and read! magic_number = struct.unpack('= 8: SUPPORTS_COLOR = True