python - 在 Python 3 中将异常转换为字符串

标签 python exception unicode character-encoding

有人知道为什么这个 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/

相关文章:

python - 评估列表理解性能后对效率的困惑

python - 如何正确弃用 Python 中的自定义异常?

java - 为什么我不能用 try/catch 子句处理 Exception e?

c# - 如何正确使用XNA的SetData方法

python - 规范化 Unicode

python - RopeVim 中的代码辅助......你如何使用它?

python - Maya 的 ShrinkWrap 变形器

python - 当我运行 `for glyph in font.iter(' glyph')` 时,为什么 etree 没有从我的 SVG 中返回任何内容?

mysql - 包含 UTF8 字符的旧条目错误地保存在 UTF8 数据库中

python - Unicode解码错误: 'utf8' codec can't decode byte 0xa9 in position 1