Python 将异常错误转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37684153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:47:58  来源:igfitidea点击:

Convert exception error to string

python

提问by dpetican

I want to work with the error message from an exception but can't seem to convert it to a string. I've read the os library man page but something is not clicking for me.

我想处理来自异常的错误消息,但似乎无法将其转换为字符串。我已经阅读了 os 库手册页,但我没有点击。

Printing the error works:

打印错误有效:

try:
    os.open("test.txt", os.O_RDONLY)
except OSError as err:
    print ("I got this error: ", err)

But this does not:

但这不会:

try:
    os.open("test.txt", os.O_RDONLY)
except OSError as err:
    print ("I got this error: " + err)

TypeError: Can't convert 'FileNotFoundError' object to str implicitly

回答by Hendy Irawan

In my experience what you want is repr(err), which will return both the exception type and the message.

根据我的经验,您想要的是repr(err),它将返回异常类型和消息。

str(err)only gives the message.

str(err)只给出消息。

回答by miradulo

From the docs for print()

文档中print()

All non-keyword arguments are converted to strings like str() does and written to the stream

所有非关键字参数都像 str() 那样转换为字符串并写入流

So in the first case, your error is converted to a string by the printbuilt-in, whereas no such conversion takes place when you just try and concatenate your error to a string. So, to replicate the behavior of passing the message and the error as separate arguments, you must convert your error to a string with str().

因此,在第一种情况下,您的错误会被print内置函数转换为字符串,而当您尝试将错误连接到字符串时,不会发生这种转换。因此,要复制将消息和错误作为单独参数传递的行为,您必须将错误转换为带有str().