Python colorama.AnsiToWin32() Examples

The following are 30 code examples of colorama.AnsiToWin32(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama , or try the search function .
Example #1
Source File: logger.py    From brutemap with GNU General Public License v3.0 6 votes vote down vote up
def colored(self):
        """
        Cek jika pesan bisa di warnai
        """

        _ = self.stream
        if isinstance(_, AnsiToWin32):
            _ = _.wrapped

        if hasattr(_, "isatty") and _.isatty():
            return True

        if os.getenv("TERM", "").lower() == "ansi":
            return True

        return False 
Example #2
Source File: terminalwriter.py    From py with MIT License 6 votes vote down vote up
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 
Example #3
Source File: terminalwriter.py    From python-netsurv with MIT License 6 votes vote down vote up
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 
Example #4
Source File: terminalwriter.py    From python-netsurv with MIT License 6 votes vote down vote up
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 
Example #5
Source File: misc.py    From pipenv with MIT License 6 votes vote down vote up
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 
Example #6
Source File: terminalwriter.py    From pytest with MIT License 6 votes vote down vote up
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 
Example #7
Source File: misc.py    From vistir with ISC License 6 votes vote down vote up
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 
Example #8
Source File: logger.py    From brutemap with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, stream):
        logging.StreamHandler.__init__(self, stream)

        if IS_WINDOWS:
            stream = AnsiToWin32(stream)

        self.stream = stream
        self.record = None 
Example #9
Source File: log.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _init_handlers(
        level: int,
        color: bool,
        force_color: bool,
        json_logging: bool,
        ram_capacity: int
) -> typing.Tuple[logging.StreamHandler, typing.Optional['RAMHandler']]:
    """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  # type: ignore[unreachable]
    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.DEBUG)
        ram_handler.setFormatter(ram_fmt)
        ram_handler.html_formatter = html_fmt

    return console_handler, ram_handler 
Example #10
Source File: text.py    From linter-pylama with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: _compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
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 
Example #12
Source File: _compat.py    From jbox with MIT License 5 votes vote down vote up
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 
Example #13
Source File: _compat.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #14
Source File: text.py    From python-netsurv with MIT License 5 votes vote down vote up
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 colorama

                self.out = colorama.AnsiToWin32(self.out) 
Example #15
Source File: text.py    From python-netsurv with MIT License 5 votes vote down vote up
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 colorama

                self.out = colorama.AnsiToWin32(self.out) 
Example #16
Source File: io.py    From Beehive with GNU General Public License v3.0 5 votes vote down vote up
def bprint(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 + \
                  msgStr + \
                  colorama.Fore.RESET + \
                  colorama.Style.RESET_ALL,
              file=stream) 
Example #17
Source File: io.py    From Beehive with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #18
Source File: _compat.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
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 
Example #19
Source File: misc.py    From pipenv with MIT License 5 votes vote down vote up
def _is_wrapped_for_color(stream):
            return isinstance(
                stream, (colorama.AnsiToWin32, colorama.ansitowin32.StreamWrapper)
            ) 
Example #20
Source File: _compat.py    From pipenv with MIT License 5 votes vote down vote up
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 
Example #21
Source File: colored_traceback.py    From colored-traceback.py with ISC License 5 votes vote down vote up
def stream(self):
        try:
            import colorama
            return colorama.AnsiToWin32(sys.stderr)
        except ImportError:
            return sys.stderr 
Example #22
Source File: _compat.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
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 
Example #23
Source File: _compat.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
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 
Example #24
Source File: _compat.py    From scylla with Apache License 2.0 5 votes vote down vote up
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 
Example #25
Source File: terminalwriter.py    From scylla with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: _compat.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
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 
Example #27
Source File: _compat.py    From planespotter with MIT License 5 votes vote down vote up
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 
Example #28
Source File: _compat.py    From rules_pip with MIT License 5 votes vote down vote up
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 
Example #29
Source File: _compat.py    From hitch with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #30
Source File: _compat.py    From be with GNU Lesser General Public License v2.1 5 votes vote down vote up
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