python强转字符串_在Python 3中将Exception转换为字符串

在Python 3中将Exception转换为字符串

有谁知道,为什么这个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:强制转换为str:需要字节,bytearray或类似缓冲区的对象,是否发现异常?

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

编辑

如果消息中有 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()无法在内部将异常转换为字节?

5个解决方案

47 votes

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

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

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

Aaron Digulla answered 2020-06-17T07:53:06Z

11 votes

试试这个,它应该起作用。

try:

raise Exception(X)

except Exception as e:

print("Error {0}".format(str(e.args[0])).encode("utf-8"))

考虑到内部元组中只有一条消息。

Sebastiano Merlino answered 2020-06-17T07:53:31Z

4 votes

在Python3中,string没有诸如编码之类的属性。 内部始终是unicode。 对于编码的字符串,有字节数组:

s = "Error {0}".format(str(e)) # string

utf8str = s.encode("utf-8") # byte array, representing utf8-encoded text

hamstergene answered 2020-06-17T07:53:51Z

3 votes

在Python 3中,您已经处在“ unicode空间”中,不需要编码。 根据您要实现的目标,您应该在完成工作之前立即进行转换。

例如。 您可以将所有这些都转换为bytes(),而应将其转换为

bytes("Error {0}".format(str(e)), encoding=utf-8)

.

glglgl answered 2020-06-17T07:54:19Z

1 votes

这里有与版本无关的转换:

# from the `six` library

import sys

PY2 = sys.version_info[0] == 2

if PY2:

text_type = unicode

binary_type = str

else:

text_type = str

binary_type = bytes

def exc2str(e):

if e.args and isinstance(e.args[0], binary_type):

return e.args[0].decode(utf-8)

return text_type(e)

并对其进行测试:

def test_exc2str():

a = u"u0856"

try:

raise ValueError(a)

except ValueError as e:

assert exc2str(e) == a

assert isinstance(exc2str(e), text_type)

try:

raise ValueError(a.encode(utf-8))

except ValueError as e:

assert exc2str(e) == a

assert isinstance(exc2str(e), text_type)

try:

raise ValueError()

except ValueError as e:

assert exc2str(e) ==

assert isinstance(exc2str(e), text_type)

tsionyx answered 2020-06-17T07:54:43Z

经验分享 程序员 微信小程序 职场和发展