Fix prints()

This commit is contained in:
Kovid Goyal 2019-12-19 08:12:00 +05:30
parent 4d40be05f3
commit 1d33b3dc0c
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -18,14 +18,28 @@ def is_binary(stream):
def prints(*a, **kw):
' Print either unicode or bytes to either binary or text mode streams '
stream = kw.get('file', sys.stdout)
sep, end = kw.get('sep'), kw.get('end')
if sep is None:
sep = ' '
if end is None:
end = '\n'
if is_binary(stream):
encoding = getattr(stream, 'encoding', None) or 'utf-8'
a = tuple(as_bytes(x, encoding=encoding) for x in a)
kw['sep'] = as_bytes(kw.get('sep', b' '))
kw['end'] = as_bytes(kw.get('end', b'\n'))
sep = as_bytes(sep)
end = as_bytes(end)
else:
a = tuple(as_unicode(x, errors='replace') for x in a)
kw['sep'] = as_unicode(kw.get('sep', ' '))
kw['end'] = as_unicode(kw.get('end', '\n'))
return print(*a, **kw)
sep = as_unicode(sep)
end = as_unicode(end)
for x in a:
stream.write(x)
if sep:
stream.write(sep)
if end:
stream.write(end)
if kw.get('flush'):
try:
stream.flush()
except Exception:
pass