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

ts.*_*ts. 48 python unicode exception character-encoding

有没有人有一个想法,为什么这个Python 3.2代码

try:    
    raise Exception('X')
except Exception as e:
    print("Error {0}".format(str(e)))
Run Code Online (Sandbox Code Playgroud)

工作没有问题(除了Windows shell中的unicode编码:/),但这

try:    
    raise Exception('X')
except Exception as e:
    print("Error {0}".format(str(e, encoding = 'utf-8')))
Run Code Online (Sandbox Code Playgroud)

抛出TypeError:强制转换为str:需要字节,字节数组或缓冲区对象,发现异常

如何使用自定义编码将错误转换为字符串?

编辑

如果消息中有\ 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')))
Run Code Online (Sandbox Code Playgroud)

但是为什么str()不能在内部将异常转换为字节?

Aar*_*lla 48

在Python 3.x中,str(e)应该能够将any转换Exception为字符串,即使它包含Unicode字符.

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

我的猜测是你的问题不是,str()而是print()(即将Python Unicode字符串转换为在控制台上转储的东西的步骤).请参阅此答案以获取解决方案:Python,Unicode和Windows控制台


Seb*_*ino 12

试试这个,它应该工作.

try:    
    raise Exception('X')
except Exception as e:
    print("Error {0}".format(str(e.args[0])).encode("utf-8"))
Run Code Online (Sandbox Code Playgroud)

考虑到你的内部元组中只有一条消息.


ham*_*ene 5

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

s = "Error {0}".format(str(e)) # string
utf8str = s.encode("utf-8") # byte array, representing utf8-encoded text
Run Code Online (Sandbox Code Playgroud)