Esempio n. 1
0
def _init_handlers(level, color, force_color, json_logging, ram_capacity):
    """Init log handlers.

    Args:
        level: The numeric logging level.
        color: Whether to use color if available.
        force_color: Force colored output.
        json_logging: Output log lines in JSON (this disables all colors).
    """
    global ram_handler
    global console_handler
    console_fmt, ram_fmt, html_fmt, use_colorama = _init_formatters(
        level, color, force_color, json_logging)

    if sys.stderr is None:
        console_handler = None
    else:
        strip = False if force_color else None
        if use_colorama:
            stream = colorama.AnsiToWin32(sys.stderr, strip=strip)
        else:
            stream = sys.stderr
        console_handler = logging.StreamHandler(stream)
        console_handler.setLevel(level)
        console_handler.setFormatter(console_fmt)

    if ram_capacity == 0:
        ram_handler = None
    else:
        ram_handler = RAMHandler(capacity=ram_capacity)
        ram_handler.setLevel(logging.NOTSET)
        ram_handler.setFormatter(ram_fmt)
        ram_handler.html_formatter = html_fmt

    return console_handler, ram_handler
Esempio n. 2
0
def bprintPrefix(msgStr, msgType=None, vbCur=1, vbTs=1):
    '''
    print function with:
        1. diffrent message type with different color:
            info - default color
            warning - yellow
            error - red
            ok - green
        2. verbose level control.
    args:
        msgStr - the message string.
        msgType - message type(info/warning/error/ok).
        vbCur - current verbose level.
        vbTs - verbose threshold to print the message.
    '''
    if vbCur >= vbTs:
        # deprecated, because colorama.init() disables the auto-completion
        # of cmd2, although it works very well in platform auto-detection.
        #colorama.init(autoreset=True)

        if platform.system().lower() == 'windows':
            stream = colorama.AnsiToWin32(sys.stdout)
        else:
            stream = sys.stdout

        print(msgTypeColor[msgType][0] + \
                  colorama.Style.BRIGHT + \
                  msgTypeColor[msgType][1] + \
                  colorama.Fore.RESET + \
                  colorama.Style.RESET_ALL,
              end='',
              file=stream)
        print(msgStr, file=stream)
Esempio n. 3
0
def _init_handlers(level, color, ram_capacity):
    """Init log handlers.

    Args:
        level: The numeric logging level.
        color: Whether to use color if available.
    """
    global ram_handler
    console_fmt, ram_fmt, html_fmt, use_colorama = _init_formatters(
        level, color)

    if sys.stderr is None:
        console_handler = None
    else:
        if use_colorama:
            stream = colorama.AnsiToWin32(sys.stderr)
        else:
            stream = sys.stderr
        console_handler = logging.StreamHandler(stream)
        console_handler.setLevel(level)
        console_handler.setFormatter(console_fmt)

    if ram_capacity == 0:
        ram_handler = None
    else:
        ram_handler = RAMHandler(capacity=ram_capacity)
        ram_handler.setLevel(logging.NOTSET)
        ram_handler.setFormatter(ram_fmt)
        ram_handler.html_formatter = html_fmt

    return console_handler, ram_handler
Esempio n. 4
0
    def out(self, obj, formatter=None, out_file=None):  # pylint: disable=no-self-use
        """ Produces the output using the command result.
            The method does not return a result as the output is written straight to the output file.

        :param obj: The command result
        :type obj: knack.util.CommandResultItem
        :param formatter: The formatter we should use for the command result
        :type formatter: function
        :param out_file: The file to write output to
        :type out_file: file-like object
        """
        if not isinstance(obj, CommandResultItem):
            raise TypeError('Expected {} got {}'.format(CommandResultItem.__name__, type(obj)))

        import platform
        import colorama

        if platform.system() == 'Windows':
            out_file = colorama.AnsiToWin32(out_file).stream
        output = formatter(obj)
        try:
            print(output, file=out_file, end='')
        except IOError as ex:
            if ex.errno == errno.EPIPE:
                pass
            else:
                raise
        except UnicodeEncodeError:
            print(output.encode('ascii', 'ignore').decode('utf-8', 'ignore'),
                  file=out_file, end='')
Esempio n. 5
0
 def __init__(self, output=None, color_mapping=None):
     TextReporter.__init__(self, output)
     self.color_mapping = color_mapping or \
                          dict(ColorizedTextReporter.COLOR_MAPPING)
     if sys.platform == 'win32':
         import colorama
         self.out = colorama.AnsiToWin32(self.out)
Esempio n. 6
0
    def auto_wrap_for_ansi(stream: t.TextIO,
                           color: t.Optional[bool] = None) -> t.TextIO:
        """Support ANSI color and style codes on Windows by wrapping a
        stream with colorama.
        """
        try:
            cached = _ansi_stream_wrappers.get(stream)
        except Exception:
            cached = None

        if cached is not None:
            return cached

        import colorama

        strip = should_strip_ansi(stream, color)
        ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
        rv = t.cast(t.TextIO, ansi_wrapper.stream)
        _write = rv.write

        def _safe_write(s):
            try:
                return _write(s)
            except BaseException:
                ansi_wrapper.reset_all()
                raise

        rv.write = _safe_write

        try:
            _ansi_stream_wrappers[stream] = rv
        except Exception:
            pass

        return rv
Esempio n. 7
0
    def __init__(
        self,
        output: Optional[TextIO] = None,
        color_mapping: Union[
            ColorMappingDict, Dict[str, Tuple[Optional[str], Optional[str]]], None
        ] = None,
    ) -> None:
        super().__init__(output)
        # pylint: disable-next=fixme
        # TODO: Remove DeprecationWarning and only accept ColorMappingDict as color_mapping parameter
        if color_mapping and not isinstance(
            list(color_mapping.values())[0], MessageStyle
        ):
            warnings.warn(
                "In pylint 3.0, the ColoreziedTextReporter will only accept ColorMappingDict as color_mapping parameter",
                DeprecationWarning,
            )
            temp_color_mapping: ColorMappingDict = {}
            for key, value in color_mapping.items():
                color = value[0]
                style_attrs = tuple(_splitstrip(value[1]))
                temp_color_mapping[key] = MessageStyle(color, style_attrs)
            color_mapping = temp_color_mapping
        else:
            color_mapping = cast(Optional[ColorMappingDict], color_mapping)
        self.color_mapping = color_mapping or ColorizedTextReporter.COLOR_MAPPING
        ansi_terms = ["xterm-16color", "xterm-256color"]
        if os.environ.get("TERM") not in ansi_terms:
            if sys.platform == "win32":
                # pylint: disable=import-error,import-outside-toplevel
                import colorama

                self.out = colorama.AnsiToWin32(self.out)
Esempio n. 8
0
 def __init__(self, stream=None):
     super().__init__(stream=stream)
     tty = hasattr(self.stream, 'isatty') and self.stream.isatty()
     self.stream = colorama.AnsiToWin32(
         self.stream,
         strip=None if tty else True,
         autoreset=True).stream
Esempio n. 9
0
        def auto_wrap_for_ansi(stream, color=None):
            """This function wraps a stream so that calls through colorama
            are issued to the win32 console API to recolor on demand.  It
            also ensures to reset the colors if a write call is interrupted
            to not destroy the console afterwards.
            """
            try:
                cached = _ansi_stream_wrappers.get(stream)
            except Exception:
                cached = None
            if cached is not None:
                return cached
            strip = should_strip_ansi(stream, color)
            ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
            rv = ansi_wrapper.stream
            _write = rv.write

            def _safe_write(s):
                try:
                    return _write(s)
                except:
                    ansi_wrapper.reset_all()
                    raise

            rv.write = _safe_write
            try:
                _ansi_stream_wrappers[stream] = rv
            except Exception:
                pass
            return rv
Esempio n. 10
0
 def __init__(self, log_level_config, log_format):
     logging.StreamHandler.__init__(self)
     self.setLevel(log_level_config)
     if platform.system() == 'Windows':
         self.stream = colorama.AnsiToWin32(self.stream).stream
     self.enable_color = self._should_enable_color()
     self.setFormatter(logging.Formatter(log_format[self.enable_color]))
Esempio n. 11
0
    def stream(self):
        try:
            import colorama

            return colorama.AnsiToWin32(sys.stderr)
        except ImportError:
            return sys.stderr
Esempio n. 12
0
    def process(self, data):
        colorize = not self.args.gray and not self.args.stdout
        if os.name == 'nt' and not self.isatty:
            # coloring stderr does not work properly in Windows when stdout is redirected:
            # https://github.com/tartley/colorama/issues/200
            colorize = False
        lines = self._peeklines(data, colorize)

        if self.args.stdout:
            for line in lines:
                yield line.encode(self.codec)
            return

        stderr = sys.stderr

        if colorize:
            colorama = self._colorama
            if os.name == 'nt':
                stderr = colorama.AnsiToWin32(stderr).stream
            _erase = ' ' * get_terminal_size()
            _reset = F'\r{colorama.Style.RESET_ALL}{_erase}\r'
        else:
            _reset = ''

        try:
            for line in lines:
                print(line, file=stderr)
        except BaseException:
            stderr.write(_reset)
            raise
        if not self.isatty:
            self.log_info('forwarding input to next unit')
            yield data
Esempio n. 13
0
    def __init__(self, *args, **kwargs):
        # The Windows terminal does not support the hide/show cursor ANSI codes
        # even with colorama. So we'll ensure that hide_cursor is False on
        # Windows.
        # This call neds to go before the super() call, so that hide_cursor
        # is set in time. The base progress bar class writes the "hide cursor"
        # code to the terminal in its init, so if we don't set this soon
        # enough, we get a "hide" with no corresponding "show"...
        if WINDOWS and self.hide_cursor:
            self.hide_cursor = False

        super(WindowsMixin, self).__init__(*args, **kwargs)

        # Check if we are running on Windows and we have the colorama module,
        # if we do then wrap our file with it.
        if WINDOWS and colorama:
            self.file = colorama.AnsiToWin32(self.file)
            # The progress code expects to be able to call self.file.isatty()
            # but the colorama.AnsiToWin32() object doesn't have that, so we'll
            # add it.
            self.file.isatty = lambda: self.file.wrapped.isatty()
            # The progress code expects to be able to call self.file.flush()
            # but the colorama.AnsiToWin32() object doesn't have that, so we'll
            # add it.
            self.file.flush = lambda: self.file.wrapped.flush()
Esempio n. 14
0
        def _wrap_for_color(stream, color=None):
            try:
                cached = _color_stream_cache.get(stream)
            except KeyError:
                cached = None
            if cached is not None:
                return cached
            strip = not _can_use_color(stream, color)
            _color_wrapper = colorama.AnsiToWin32(stream, strip=strip)
            result = _color_wrapper.stream
            _write = result.write

            def _write_with_color(s):
                try:
                    return _write(s)
                except Exception:
                    _color_wrapper.reset_all()
                    raise

            result.write = _write_with_color
            try:
                _color_stream_cache[stream] = result
            except Exception:
                pass
            return result
Esempio n. 15
0
 def __init__(self, output=None, color_mapping=None):
     TextReporter.__init__(self, output)
     self.color_mapping = color_mapping or \
                          dict(ColorizedTextReporter.COLOR_MAPPING)
     ansi_terms = ['xterm-16color', 'xterm-256color']
     if os.environ.get('TERM') not in ansi_terms:
         if sys.platform == 'win32':
             import colorama
             self.out = colorama.AnsiToWin32(self.out)
Esempio n. 16
0
    def __init__(self) -> None:
        try:
            import colorama
        except ImportError:
            stream = None
        else:
            stream = colorama.AnsiToWin32(sys.stderr)

        super().__init__(stream)
Esempio n. 17
0
    def __init__(self, output=None, color_mapping=None):
        TextReporter.__init__(self, output)
        self.color_mapping = color_mapping or dict(ColorizedTextReporter.COLOR_MAPPING)
        ansi_terms = ["xterm-16color", "xterm-256color"]
        if os.environ.get("TERM") not in ansi_terms:
            if sys.platform == "win32":
                # pylint: disable=import-error,import-outside-toplevel
                import colorama

                self.out = colorama.AnsiToWin32(self.out)
Esempio n. 18
0
 def add_consumers(self, *consumers):
     if sys.platform.startswith("win"):
         for level, consumer in consumers:
             if hasattr(consumer, "write"):
                 self.consumers.append(
                     (level, colorama.AnsiToWin32(consumer)), )
             else:
                 self.consumers.append((level, consumer))
     else:
         self.consumers.extend(consumers)
Esempio n. 19
0
def prepare_terminal():
    try:
        # Optionally fix colors on Windows and in journals if the colorama module
        # is available.
        import colorama

        wrapper = colorama.AnsiToWin32(sys.stdout)
        if wrapper.should_wrap():
            sys.stdout = wrapper.stream
    except ImportError:
        pass
Esempio n. 20
0
    def __init__(self, stream, logger, level_manager):
        super(ColorizedStreamHandler, self).__init__(stream)

        if platform.system() == 'Windows':
            self.stream = colorama.AnsiToWin32(self.stream).stream

        fmt = self.CONSOLE_LOG_FORMAT[logger.name][self.enable_color]
        super(ColorizedStreamHandler,
              self).setFormatter(logging.Formatter(fmt))
        super(ColorizedStreamHandler,
              self).setLevel(level_manager.get_user_setting_level(logger))
Esempio n. 21
0
		def auto_wrap_for_ansi(stream,color=_A):
			A=stream
			try:C=_ansi_stream_wrappers.get(A)
			except Exception:C=_A
			if C is not _A:return C
			E=should_strip_ansi(A,color);D=colorama.AnsiToWin32(A,strip=E);B=D.stream;F=B.write
			def G(s):
				try:return F(s)
				except BaseException:D.reset_all();raise
			B.write=G
			try:_ansi_stream_wrappers[A]=B
			except Exception:pass
			return B
Esempio n. 22
0
 def auto_wrap_for_ansi(stream):
     try:
         cached = _ansi_stream_wrappers.get(stream)
     except Exception:
         cached = None
     if cached is not None:
         return cached
     strip = not isatty(stream)
     rv = colorama.AnsiToWin32(stream, strip=strip).stream
     try:
         _ansi_stream_wrappers[stream] = rv
     except Exception:
         pass
     return rv
Esempio n. 23
0
 def __init__(self, stream=sys.stderr):
     if HAVE_COLORAMA:
         logging.StreamHandler.__init__(self, colorama.AnsiToWin32(stream).stream)
     else:
         logging.StreamHandler.__init__(self, stream)
     
     # Hold log records for 0.5 sec before printing them to allow sorting
     # by creation time.
     self.delay = 0.2
     self.record_lock = threading.Lock()
     self.records = []
     self.thread = threading.Thread(target=self.poll_records, daemon=True)
     self.thread.start()
     atexit.register(self.flush_records)
Esempio n. 24
0
 def __init__(self, file=None, stringio=False, encoding=None):
     if file is None:
         if stringio:
             self.stringio = file = py.io.TextIO()
         else:
             file = py.std.sys.stdout
     elif py.builtin.callable(file) and not (
          hasattr(file, "write") and hasattr(file, "flush")):
         file = WriteFile(file, encoding=encoding)
     if hasattr(file, "isatty") and file.isatty() and colorama:
         file = colorama.AnsiToWin32(file).stream
     self.encoding = encoding or getattr(file, 'encoding', "utf-8")
     self._file = file
     self.hasmarkup = should_do_markup(file)
     self._lastlen = 0
Esempio n. 25
0
 def out(self, obj):
     if platform.system() == 'Windows':
         self.file = colorama.AnsiToWin32(self.file).stream
     output = self.formatter(obj)
     try:
         print(output, file=self.file, end='')
     except IOError as ex:
         if ex.errno == errno.EPIPE:
             pass
         else:
             raise
     except UnicodeEncodeError:
         print(output.encode('ascii', 'ignore').decode('utf-8', 'ignore'),
               file=self.file,
               end='')
Esempio n. 26
0
 def __init__(self, file: Optional[TextIO] = None) -> None:
     if file is None:
         file = sys.stdout
     if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32":
         try:
             import colorama
         except ImportError:
             pass
         else:
             file = colorama.AnsiToWin32(file).stream
             assert file is not None
     self._file = file
     self.hasmarkup = should_do_markup(file)
     self._current_line = ""
     self._terminal_width = None  # type: Optional[int]
     self.code_highlight = True
Esempio n. 27
0
    def __init__(self,
                 art: str = None,
                 display_art: bool = True,
                 colour: str = "cyan",
                 art_colour: str = None):
        self.spacing = 0
        self.art = art
        self.display_art = display_art

        self.colour = self.colours(colour)
        self.art_colour = self.colours(art_colour)

        self.bright = colorama.Style.BRIGHT
        self.resetc = colorama.Style.RESET_ALL

        self.stream = colorama.AnsiToWin32(sys.stdout).stream
        colorama.init(wrap=False)
Esempio n. 28
0
 def __init__(self, file=None, stringio=False, encoding=None):
     if file is None:
         if stringio:
             self.stringio = file = py.io.TextIO()
         else:
             from sys import stdout as file
     elif py.builtin.callable(file) and not (hasattr(file, "write")
                                             and hasattr(file, "flush")):
         file = WriteFile(file, encoding=encoding)
     if hasattr(file, "isatty") and file.isatty() and colorama:
         file = colorama.AnsiToWin32(file).stream
     self.encoding = encoding or getattr(file, "encoding", "utf-8")
     self._file = file
     self.hasmarkup = should_do_markup(file)
     self._lastlen = 0
     self._chars_on_current_line = 0
     self._width_of_current_line = 0
Esempio n. 29
0
 def __init__(self, port_instance: StreamDevice, transformations=(),
              output_raw: bool = False, request_banner: bool = True):
     self.device = port_instance
     self.device.subscribe(b'sout')
     self.device.subscribe(b'serr')
     self.transformations = transformations
     self._reader_alive = None
     self.receiver_thread = None  # type: threading.Thread
     self._transmitter_alive = None
     self.transmitter_thread = None  # type: threading.Thread
     self.alive = threading.Event()  # type: threading.Event
     self.output_raw = output_raw
     self.request_banner = request_banner
     self.no_sigint = True  # SIGINT flag
     signal.signal(signal.SIGINT, self.catch_sigint)  # SIGINT handler
     self.console = Console()
     self.console.output = colorama.AnsiToWin32(self.console.output).stream
Esempio n. 30
0
 def __init__(self):
     super(Console, self).__init__()
     self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP()
     self._saved_icp = ctypes.windll.kernel32.GetConsoleCP()
     ctypes.windll.kernel32.SetConsoleOutputCP(65001)
     ctypes.windll.kernel32.SetConsoleCP(65001)
     if colorama:
         self.output = colorama.AnsiToWin32(
             codecs.getwriter('UTF-8')(Out(sys.stdout.fileno()),
                                       'replace')).stream
     else:
         self.output = codecs.getwriter('UTF-8')(Out(
             sys.stdout.fileno()), 'replace')
     # the change of the code page is not propagated to Python, manually fix it
     sys.stderr = codecs.getwriter('UTF-8')(Out(sys.stderr.fileno()),
                                            'replace')
     sys.stdout = self.output
     self.output.encoding = 'UTF-8'  # needed for input