1
0
mirror of https://github.com/openSUSE/osc.git synced 2025-08-26 08:08:55 +02:00

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.
This commit is contained in:
Marcus Huewe
2018-03-09 16:50:09 +01:00
parent 305501f92c
commit caaefb0bf5

View File

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