Handle utf-8 output encoding in py3 also. Fixes #382

This commit is contained in:
Matt Martz 2017-04-10 15:32:14 -05:00
parent 2e79fbf1dc
commit 1642d0669f
1 changed files with 22 additions and 4 deletions

View File

@ -135,7 +135,7 @@ try:
BytesIO = None BytesIO = None
except ImportError: except ImportError:
try: try:
from io import StringIO, BytesIO from io import StringIO, BytesIO, TextIOWrapper, FileIO
except ImportError: except ImportError:
from StringIO import StringIO from StringIO import StringIO
BytesIO = None BytesIO = None
@ -158,7 +158,7 @@ except ImportError:
if not isinstance(data, basestring): if not isinstance(data, basestring):
data = str(data) data = str(data)
# If the file has an encoding, encode unicode with it. # If the file has an encoding, encode unicode with it.
encoding = 'UTF-8' # Always trust UTF-8 for output encoding = 'utf8' # Always trust UTF-8 for output
if (isinstance(fp, file) and if (isinstance(fp, file) and
isinstance(data, unicode) and isinstance(data, unicode) and
encoding is not None): encoding is not None):
@ -203,8 +203,26 @@ except ImportError:
write(arg) write(arg)
write(end) write(end)
else: else:
print_ = getattr(builtins, 'print') class _Py3Utf8Stdout(TextIOWrapper):
del builtins def __init__(self, **kwargs):
buf = FileIO(sys.stdout.fileno(), 'w')
super(_Py3Utf8Stdout, self).__init__(
buf,
encoding='utf8',
errors='strict'
)
def write(self, s):
super(_Py3Utf8Stdout, self).write(s)
self.flush()
_py3_print = getattr(builtins, 'print')
_py3_utf8_stdout = _Py3Utf8Stdout()
def print_(*args, **kwargs):
kwargs['file'] = _py3_utf8_stdout
_py3_print(*args, **kwargs)
# Exception "constants" to support Python 2 through Python 3 # Exception "constants" to support Python 2 through Python 3
try: try: