2011-02-11 02:43:10 +01:00
|
|
|
# be careful when debugging this code:
|
|
|
|
# don't add print statements when setting sys.stdout = SafeWriter(sys.stdout)...
|
2022-07-28 19:11:29 +02:00
|
|
|
class SafeWriter:
|
2011-02-11 02:43:10 +01:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2022-09-12 15:40:48 +02:00
|
|
|
|
2011-02-11 02:43:10 +01:00
|
|
|
def __init__(self, writer, encoding='unicode_escape'):
|
2018-03-09 16:50:09 +01:00
|
|
|
self._writer = writer
|
|
|
|
self._encoding = encoding
|
2011-02-11 02:43:10 +01:00
|
|
|
|
|
|
|
def write(self, s):
|
|
|
|
try:
|
2018-03-09 16:50:09 +01:00
|
|
|
self._writer.write(s)
|
2013-04-09 11:27:02 +02:00
|
|
|
except UnicodeEncodeError as e:
|
2018-03-09 16:50:09 +01:00
|
|
|
self._writer.write(s.encode(self._encoding))
|
2011-02-11 02:43:10 +01:00
|
|
|
|
|
|
|
def __getattr__(self, name):
|
2018-03-09 16:50:09 +01:00
|
|
|
return getattr(self._writer, name)
|
2011-02-11 02:43:10 +01:00
|
|
|
|
|
|
|
def __setattr__(self, name, value):
|
2022-07-28 19:11:29 +02:00
|
|
|
super().__setattr__(name, value)
|