mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-07-08 10:44:09 -04:00
Make logging more robust on legacy platforms that don't use UTF-8 for their console encoding
This commit is contained in:
parent
e15c24169c
commit
f4b4ac9f12
@ -93,21 +93,36 @@ def sanitize_file_name(name, substitute='_', as_unicode=False):
|
|||||||
def prints(*args, **kwargs):
|
def prints(*args, **kwargs):
|
||||||
'''
|
'''
|
||||||
Print unicode arguments safely by encoding them to preferred_encoding
|
Print unicode arguments safely by encoding them to preferred_encoding
|
||||||
Has the same signature as the print function from Python 3.
|
Has the same signature as the print function from Python 3, except for the
|
||||||
|
additional keyword argument safe_encode, which if set to True will cause the
|
||||||
|
function to use repr when encoding fails.
|
||||||
'''
|
'''
|
||||||
file = kwargs.get('file', sys.stdout)
|
file = kwargs.get('file', sys.stdout)
|
||||||
sep = kwargs.get('sep', ' ')
|
sep = kwargs.get('sep', ' ')
|
||||||
end = kwargs.get('end', '\n')
|
end = kwargs.get('end', '\n')
|
||||||
enc = preferred_encoding
|
enc = preferred_encoding
|
||||||
|
safe_encode = kwargs.get('safe_encode', False)
|
||||||
if 'CALIBRE_WORKER' in os.environ:
|
if 'CALIBRE_WORKER' in os.environ:
|
||||||
enc = 'utf-8'
|
enc = 'utf-8'
|
||||||
for i, arg in enumerate(args):
|
for i, arg in enumerate(args):
|
||||||
if isinstance(arg, unicode):
|
if isinstance(arg, unicode):
|
||||||
arg = arg.encode(enc)
|
try:
|
||||||
|
arg = arg.encode(enc)
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
if not safe_encode:
|
||||||
|
raise
|
||||||
|
arg = repr(arg)
|
||||||
if not isinstance(arg, str):
|
if not isinstance(arg, str):
|
||||||
arg = str(arg)
|
arg = str(arg)
|
||||||
if not isinstance(arg, unicode):
|
if not isinstance(arg, unicode):
|
||||||
arg = arg.decode(preferred_encoding, 'replace').encode(enc)
|
arg = arg.decode(preferred_encoding, 'replace')
|
||||||
|
try:
|
||||||
|
arg = arg.encode(enc)
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
if not safe_encode:
|
||||||
|
raise
|
||||||
|
arg = repr(arg)
|
||||||
|
|
||||||
file.write(arg)
|
file.write(arg)
|
||||||
if i != len(args)-1:
|
if i != len(args)-1:
|
||||||
file.write(sep)
|
file.write(sep)
|
||||||
|
@ -20,7 +20,7 @@ class Stream(object):
|
|||||||
|
|
||||||
def __init__(self, stream):
|
def __init__(self, stream):
|
||||||
from calibre import prints
|
from calibre import prints
|
||||||
self._prints = prints
|
self._prints = partial(prints, safe_encode=True)
|
||||||
self.stream = stream
|
self.stream = stream
|
||||||
|
|
||||||
def flush(self):
|
def flush(self):
|
||||||
|
Loading…
x
Reference in New Issue
Block a user