Skip to content

Instantly share code, notes, and snippets.

@danny0838
Last active December 18, 2017 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny0838/866077e30306a14247e9 to your computer and use it in GitHub Desktop.
Save danny0838/866077e30306a14247e9 to your computer and use it in GitHub Desktop.
Prevent codec error when printing to stdout in Python3
#!/usr/bin/env python3
import sys
def safeprint(*args, errors='backslashreplace', **kargs):
"""
Print safely and skips error decode.
Acts like print() with an additional "errors" argument to determine the
error handler for codec errors and accepts non-str-or-None types for the
"sep" and "end" arguments.
"""
e = (kargs['file'] if 'file' in kargs else sys.stdout).encoding
args = [str(x) for x in args]
sep = str(kargs['sep']) if 'sep' in kargs and kargs['sep'] is not None else " "
end = str(kargs['end']) if 'end' in kargs and kargs['end'] is not None else "\n"
text = sep.join(args) + end
kargs['sep'] = ""
kargs['end'] = ""
print(text.encode(e, errors).decode(e, errors), **kargs)
if __name__ == "__main__":
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड")
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="ignore")
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="replace")
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="backslashreplace")
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="xmlcharrefreplace")
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", sep=str, end=None)
safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", sep=" -发- ", end=" -财- \n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment