有人知道为什么这个 Python 3.2 代码
try:
raise Exception('X')
except Exception as e:
print("Error {0}".format(str(e)))
工作没有问题(除了 windows shell 中的 unicode 编码:/), 但是这个
try:
raise Exception('X')
except Exception as e:
print("Error {0}".format(str(e, encoding = 'utf-8')))
抛出TypeError: coercing to str: need bytes, bytearray or buffer-like object, Exception found ?
如何将错误转换为自定义编码的字符串?
编辑
如果消息中有\u2019,它也不起作用:
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() 不能在内部将异常转换为字节?
最佳答案
在 Python 3.x 中,str(e)
应该能够将任何 Exception
转换为字符串,即使它包含 Unicode 字符。
因此,除非您的异常实际上在其自定义 __str__()
方法中返回一个 UTF-8 编码的字节数组,否则 str(e, 'utf-8')
不会按预期工作(它会尝试将 RAM 中的 16 位 Unicode 字符串解释为 UTF-8 编码的字节数组 ...)
我的猜测是你的问题不是 str()
而是 print()
(即将 Python Unicode 字符串转换为被转储的东西的步骤你的控制台)。有关解决方案,请参阅此答案:Python, Unicode, and the Windows console
关于python - 在 Python 3 中将异常转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075200/