【发布时间】:2011-10-27 20:38:48
【问题描述】:
有谁知道为什么这个 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() 不能在内部将异常转换为字节?
【问题讨论】:
-
你试过
str(e).encode('utf-8')吗? -
@agf 它本身返回字节而不是字符串。我可以用它来替换字节(str(e),编码='utf-8'),但我总是要做第二次转换字节=> str
-
“为什么 str() 不能转换为字节”——它怎么知道要转换成哪种编码?此外,您的新代码相当于 .format(str(e))
-
@Eugene 是对的。您应该在格式化后对其进行编码。如果您尝试使用
encoding参数,则它要求源可作为字节访问。 -
@Eugene 尝试在法文win7的windows shell中运行,你会发现不等价
标签: python exception unicode character-encoding