Converting Exception to a string in Python 3

后端 未结 5 1890
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 23:08

does anyone have an idea, why this Python 3.2 code

try:    
    raise Exception(\'X\')
except Exception as e:
    print(\"Error {0}\".format(str(e)))

5条回答
  •  深忆病人
    2021-02-04 23:58

    There is a version-agnostic conversion here:

    # from the `six` library
    import sys
    PY2 = sys.version_info[0] == 2
    if PY2:
        text_type = unicode
        binary_type = str
    else:
        text_type = str
        binary_type = bytes
    
    def exc2str(e):
        if e.args and isinstance(e.args[0], binary_type):
            return e.args[0].decode('utf-8')
        return text_type(e)
    

    and tests for it:

    def test_exc2str():
        a = u"\u0856"
        try:
            raise ValueError(a)
        except ValueError as e:
            assert exc2str(e) == a
            assert isinstance(exc2str(e), text_type)
        try:
            raise ValueError(a.encode('utf-8'))
        except ValueError as e:
            assert exc2str(e) == a
            assert isinstance(exc2str(e), text_type)
        try:
            raise ValueError()
        except ValueError as e:
            assert exc2str(e) == ''
            assert isinstance(exc2str(e), text_type)
    

提交回复
热议问题