在Python 3中将异常转换为字符串
有没有人知道,为什么这段 Python 3.2 的代码
try:
raise Exception('X')
except Exception as e:
print("Error {0}".format(str(e)))
运行得很好(除了在 Windows 命令行中的 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() 不能把一个异常内部转换成字节呢?
6 个回答
6
在Python3中,string
这个东西没有像编码这样的属性。它内部总是以unicode的形式存在。对于编码过的字符串,我们可以使用字节数组:
s = "Error {0}".format(str(e)) # string
utf8str = s.encode("utf-8") # byte array, representing utf8-encoded text
16
试试这个,应该可以用。
try:
raise Exception('X')
except Exception as e:
print("Error {0}".format(str(e.args[0])).encode("utf-8"))
假设你在内部的元组里只有一条消息。
74
在Python 3.x中,str(e)
可以把任何类型的错误信息转换成字符串,即使里面有Unicode字符也没问题。
所以,除非你的错误信息在自定义的__str__()
方法中返回的是UTF-8编码的字节数组,否则str(e, 'utf-8')
可能不会按你想的那样工作(它会试图把内存中的16位Unicode字符字符串当作UTF-8编码的字节数组来处理……)
我猜你的问题不是出在str()
上,而是出在print()
上(也就是把Python的Unicode字符串转换成可以在控制台上显示的内容的那一步)。你可以看看这个答案来找到解决办法:Python、Unicode和Windows控制台