-import codecs
import logging
import sys
+terminal_logger = logging.getLogger('terminal')
+
+
class colorize(str):
"""
Pretty simple to use::
class _Write(object):
def __init__(self, _writer=None, prefix='', suffix='', flush=False):
- # we can't set sys.stderr as the default for _writer. Otherwise
+ # we can't set sys.stderr as the default for _writer. otherwise
# pytest's capturing gets confused
- if not _writer:
- _writer = sys.stderr
- self._writer = _Write._unicode_output_stream(_writer)
- sys.stderr = self._writer
+ self._writer = _writer or sys.stderr
self.suffix = suffix
self.prefix = prefix
self.flush = flush
- @staticmethod
- def _unicode_output_stream(stream):
- # wrapper for given stream, so it can write unicode without throwing
- # exception
- # sys.stderr.encoding is None if !isatty
- encoding = stream.encoding or ''
- if encoding.upper() in ('UTF-8', 'UTF8'):
- # already using unicode encoding, nothing to do
- return stream
- encoding = encoding or 'UTF-8'
- if sys.version_info >= (3, 0):
- # try to use whatever writer class the stream was
- return stream.__class__(stream.buffer, encoding, 'replace',
- stream.newlines, stream.line_buffering)
- else:
- # in python2, stderr is but a "file"
- return codecs.getwriter(encoding)(stream, 'replace')
-
def bold(self, string):
self.write(bold(string))
self.write(string)
def write(self, line):
- self._writer.write(self.prefix + line + self.suffix)
- if self.flush:
- self._writer.flush()
+ entry = self.prefix + line + self.suffix
+
+ try:
+ self._writer.write(entry)
+ if self.flush:
+ self._writer.flush()
+ except (UnicodeDecodeError, UnicodeEncodeError):
+ try:
+ terminal_logger.info(entry.strip('\n'))
+ except (AttributeError, TypeError):
+ terminal_logger.info(entry)
def stdout(msg):