def safe_unicode(s):
'''Return unicode instance without raising an exception.
Order of assumptions:
* ASCII string or unicode object
* UTF-8 string
* Object with __str__() or __repr__() method that returns UTF-8 string or
unicode object (depending on python version)
* String in powerline.lib.encoding.get_preferred_output_encoding() encoding
* If everything failed use safe_unicode on last exception with which
everything failed
'''
try:
try:
if type(s) is bytes:
return unicode(s, 'ascii')
else:
return unicode(s)
except UnicodeDecodeError:
try:
return unicode(s, 'utf-8')
except TypeError:
return unicode(str(s), 'utf-8')
except UnicodeDecodeError:
return unicode(s, get_preferred_output_encoding())
except Exception as e:
return safe_unicode(e)
评论列表
文章目录