在Python 3中将Exception转换为字符串 [英] Converting Exception to a string in Python 3

查看:1155
本文介绍了在Python 3中将Exception转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么使用此Python 3.2代码

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)))

可以正常工作(Windows Shell中的unicode编码的一部分:/),
但这是

works without problem (apart of unicode encoding in windows shell :/), but this

try:    
    raise Exception('X')
except Exception as e:
    print("Error {0}".format(str(e, encoding = 'utf-8')))

抛出 TypeError:强制转换为str:需要字节,字节数组或类似于缓冲区的对象,发现异常

如何将错误转换为具有自定义编码的字符串?

How to convert an Error to a string with custom encoding?

编辑

如果消息中有\u2019,则也不起作用:

It does not works either, if there is \u2019 in message:

try:    
    raise Exception(msg)
except Exception as e:
    b = bytes(str(e), encoding = 'utf-8')
    print("Error {0}".format(str(b, encoding = 'utf-8')))

但是为什么str()无法在内部将异常转换为字节?

But why cannot str() convert an exception internally to bytes?

推荐答案

在Python 3.x中, str(e)应该能够将任何 Exception 转换为字符串,即使它包含Unicode字符也是如此。

In Python 3.x, str(e) should be able to convert any Exception to a string, even if it contains Unicode characters.

因此,除非您的异常实际返回了UTF在其自定义 __ str __()方法中使用-8编码的字节数组, str(e,'utf-8')将不能按预期工作(它将尝试将RAM中的16位Unicode字符串解释为UTF-8编码的字节数组...)

So unless your exception actually returns an UTF-8 encoded byte array in its custom __str__() method, str(e, 'utf-8') will not work as expected (it would try to interpret a 16bit Unicode character string in RAM as an UTF-8 encoded byte array ...)

我的猜测是您的问题不是 str(),而是 print()(即将Python Unicode字符串转换为可转储到控制台的内容的步骤)。有关解决方案,请参见以下答案: Python,Unicode和Windows控制台

My guess is that your problem isn't str() but the print() (i.e. the step which converts the Python Unicode string into something that gets dumped on your console). See this answer for solutions: Python, Unicode, and the Windows console

这篇关于在Python 3中将Exception转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆