我是靠谱客的博主 彪壮哑铃,最近开发中收集的这篇文章主要介绍python exception转字符串,在Python 3中将Exception转换为字符串,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

does anyone have an idea, why this Python 3.2 code

try:

raise Exception('X')

except Exception as e:

print("Error {0}".format(str(e)))

works without problem (apart of unicode encoding in windows shell :/),

but this

try:

raise Exception('X')

except Exception as e:

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

throws TypeError: coercing to str: need bytes, bytearray or buffer-like object, Exception found ?

How to convert an Error to a string with custom encoding?

Edit

It does not works either, if there is u2019 in message:

try:

raise Exception(msg)

except Exception as e:

b = bytes(str(e), encoding = 'utf-8')

print("Error {0}".format(str(b, encoding = 'utf-8')))

But why cannot str() convert an exception internally to bytes?

解决方案

In Python 3.x, str(e) should be able to convert any Exception to a string, even if it contains Unicode characters.

So unless your exception actually returns an UTF-8 encoded byte array in its custom __str__() method, str(e, 'utf-8') will not work as expected (it would try to interpret a 16bit Unicode character string in RAM as an UTF-8 encoded byte array ...)

My guess is that your problem isn't str() but the print() (i.e. the step which converts the Python Unicode string into something that gets dumped on your console). See this answer for solutions: Python, Unicode, and the Windows console

最后

以上就是彪壮哑铃为你收集整理的python exception转字符串,在Python 3中将Exception转换为字符串的全部内容,希望文章能够帮你解决python exception转字符串,在Python 3中将Exception转换为字符串所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部