Python 2 and 3 compatible Unicode printing method that gracefully degrades

What is the best way to get the correct character output without ascii compatible with Python 2 and 3? This is true?

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
print("ȧƈƈḗƞŧḗḓ uʍop-ǝpısdn ŧḗẋŧ ƒǿř ŧḗşŧīƞɠ")

One of the problems with this approach is that it does not competently degrade in situations where output is limited (for example) to asciior latin1. The default behavior is to throw an exception, for example:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)

... I would prefer to avoid error handling methods like 'replace' or 'backslashreplace' . Is there a way to configure sys.stdoutto use one of these methods? Is this a reasonable thing?

Unicode encoding in Python has been discussed a lot in StackOverflow, for example: How to write utf8 for standard output in a way that works with python2 and python3 , and snapshoe's answer and Martijn Pieters helpful comment . Also setting the correct encoding when sending stdout pipeline in Python .

But I still don't see a clear “better” way, especially with regard to error handling, gracefully.

+4
source share

Source: https://habr.com/ru/post/1614647/


All Articles