1
0
mirror of https://github.com/openSUSE/osc.git synced 2024-12-27 02:16:12 +01:00
github.com_openSUSE_osc/osc/util/safewriter.py
Marcus Huewe caaefb0bf5 Fix and simplify util.safewriter.SafeWriter
Storing the error encoding in an "encoding" attribute "breaks" the
python3 "input" function: In essence, builtin_input_impl does a
getattr(sys.stdout, 'encoding'), which returns our error encoding
instead of the "real" stdout encoding. In order to avoid this, we
store the error encoding in an "_encoding" attribute.

Making SafeWriter a new-style class simplifies the code a lot.
2018-03-09 16:55:56 +01:00

24 lines
832 B
Python

# be careful when debugging this code:
# don't add print statements when setting sys.stdout = SafeWriter(sys.stdout)...
class SafeWriter(object):
"""
Safely write an (unicode) str. In case of an "UnicodeEncodeError" the
the str is encoded with the "encoding" encoding.
All getattr, setattr calls are passed through to the "writer" instance.
"""
def __init__(self, writer, encoding='unicode_escape'):
self._writer = writer
self._encoding = encoding
def write(self, s):
try:
self._writer.write(s)
except UnicodeEncodeError as e:
self._writer.write(s.encode(self._encoding))
def __getattr__(self, name):
return getattr(self._writer, name)
def __setattr__(self, name, value):
super(SafeWriter, self).__setattr__(name, value)