如何在 Python 3 中打印异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41596810/
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
How to print an exception in Python 3?
提问by Haonan Chen
Right now, I catch the exception in the except Exception:
clause, and do print(exception)
. The result provides no information since it always prints <class 'Exception'>
. I knew this used to work in python 2, but how do I do it in python3?
现在,我在except Exception:
子句中捕获异常,然后执行print(exception)
. 结果不提供任何信息,因为它总是打印<class 'Exception'>
。我知道这曾经在 python 2 中工作,但我如何在 python3 中做到这一点?
回答by Noah Bogart
I'm guessing that you need to assign the Exception
to a variable. As shown in the Python 3 tutorial:
我猜你需要将 分配Exception
给一个变量。如Python 3 教程所示:
def fails():
x = 1 / 0
try:
fails()
except Exception as ex:
print(ex)
To give a brief explanation, as
is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.
简单解释一下,as
是在某些复合语句中使用的伪赋值关键字,用于将前面的语句赋值或别名给变量。
In this case, as
assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately. (This is discussed in detail in the Python 3 Language Reference: The try
Statement.)
在这种情况下,as
将捕获的异常分配给一个变量,允许存储和稍后使用有关异常的信息,而不是需要立即处理。(这在Python 3 Language Reference: The try
Statement中有详细讨论。)
The other compound statement using as
is the with
statement:
使用的另一个复合语句as
是以下with
语句:
@contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()
with opening(filename) as f:
# ...read data from f...
Here, with
statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally
statement in a neat generator package, and the as
statement assigns the generator-produced result from the context manager to a variable for extended use.
(This is discussed in detail in the Python 3 Language Reference: The with
Statement.)
在这里,with
语句用于用上下文管理器定义的方法包装块的执行。这就像try...except...finally
一个整洁的生成器包中的扩展语句,该as
语句将来自上下文管理器的生成器生成的结果分配给一个变量以供扩展使用。(这在Python 3 Language Reference: The with
Statement中有详细讨论。)
Finally, as
can be used when importing modules, to alias a module to a different (usually shorter) name:
最后,as
可以在导入模块时使用,将模块别名为不同的(通常较短)名称:
import foo.bar.baz as fbb
This is discussed in detail in the Python 3 Language Reference: The import
Statement.
这在Python 3 语言参考:import
声明中有详细讨论。
回答by rigel
These are the changes since python 2:
这些是自 python 2 以来的变化:
try:
1 / 0
except Exception as e: # (as opposed to except Exception, e:)
# ^ that will just look for two classes, Exception and e
# for the repr
print(repr(e))
# for just the message, or str(e), since print calls str under the hood
print(e)
# the arguments that the exception has been called with.
# the first one is usually the message. (OSError is different, though)
print(e.args)
You can look into the standard library module tracebackfor fancier stuff.
您可以查看标准库模块回溯以获得更好的东西。
回答by wpercy
Try
尝试
try:
x = 1/0
except Exception as e:
print(e)
this will print the representation given by e.__str__()
:
这将打印由e.__str__()
以下给出的表示:
"integer division or modulo by zero"
“整数除法或模以零”
you can also use:
您还可以使用:
print(repr(e))
which will include the Exception class name:
这将包括异常类名:
"ZeroDivisionError('integer division or modulo by zero',)"
"ZeroDivisionError('整数除法或模以零',)"
回答by caot
Here is the way I like that prints out all of the error stack.
这是我喜欢的打印所有错误堆栈的方式。
import logging
try:
1 / 0
except Exception as _e:
# any one of the follows:
# print(logging.traceback.format_exc())
logging.error(logging.traceback.format_exc())
The output looks as the follows:
输出如下所示:
ERROR:root:Traceback (most recent call last):
File "/PATH-TO-YOUR/filename.py", line 4, in <module>
1 / 0
ZeroDivisionError: division by zero
LOGGING_FORMAT
:
LOGGING_FORMAT
:
LOGGING_FORMAT = '%(asctime)s\n File "%(pathname)s", line %(lineno)d\n %(levelname)s [%(message)s]'
回答by Nicolas Huynh
I've use this :
我用过这个:
except (socket.timeout, KeyboardInterrupt) as e:
logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
break
Let me know if it does not work for you !!
如果它不适合您,请告诉我!!