unicode.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:dotfiles 作者: gbraad 项目源码 文件源码
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)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号