我如何打印错误/异常在except:块?
try:
...
except:
print(exception)
我如何打印错误/异常在except:块?
try:
...
except:
print(exception)
当前回答
Python 3:日志记录
可以使用更灵活的日志模块来记录异常,而不是使用基本的print()函数。日志模块提供了很多额外的功能,例如,日志消息…
到一个给定的日志文件,或者 带有时间戳和关于日志记录发生位置的附加信息。
欲了解更多信息,请查看官方文档。
使用
可以使用模块级函数Logging .exception()来记录异常,如下所示:
import logging
try:
1/0
except BaseException:
logging.exception("An exception was thrown!")
输出
ERROR:root:An exception was thrown!
Traceback (most recent call last):
File ".../Desktop/test.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
笔记
函数logging.exception()只能从异常处理程序调用 日志模块不应该在日志处理程序中使用,以避免RecursionError(感谢@PrakharPandey)
选择日志级别
也可以使用另一个日志级别记录异常,但仍然可以通过使用关键字参数exc_info=True显示异常细节,如下所示:
logging.critical("An exception was thrown!", exc_info=True)
logging.error ("An exception was thrown!", exc_info=True)
logging.warning ("An exception was thrown!", exc_info=True)
logging.info ("An exception was thrown!", exc_info=True)
logging.debug ("An exception was thrown!", exc_info=True)
# or the general form
logging.log(level, "An exception was thrown!", exc_info=True)
仅限名称和描述
当然,如果你不想要整个回溯,而只想要一些特定的信息(例如,异常名称和描述),你仍然可以像这样使用日志模块:
try:
1/0
except BaseException as exception:
logging.warning(f"Exception Name: {type(exception).__name__}")
logging.warning(f"Exception Desc: {exception}")
输出
WARNING:root:Exception Name: ZeroDivisionError
WARNING:root:Exception Desc: division by zero
其他回答
(我本来想把这个作为对@jldupont的回答的评论,但我没有足够的声誉。)
我在其他地方也看到过@jldupont这样的回答。FWIW,我认为有一点很重要:
except Exception as e:
print(e)
将错误输出输出到sys。默认为Stdout。一般来说,更合适的错误处理方法是:
except Exception as e:
print(e, file=sys.stderr)
(注意,你必须导入sys才能工作。)通过这种方式,错误被打印到STDERR而不是STDOUT,这允许正确的输出解析/重定向等。我知道这个问题严格来说是关于“打印错误”的,但在这里指出最佳实践而不是忽略这个细节,这可能会导致那些最终没有更好地学习的人使用非标准代码,这似乎很重要。
我没有像Cat Plus Plus的答案中那样使用traceback模块,也许这是最好的方法,但我想我要把它放在那里。
traceback模块提供了格式化和打印异常及其回溯信息的方法,例如,这将像默认处理程序一样打印异常:
import traceback
try:
1/0
except Exception:
traceback.print_exc()
输出:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
对于Python 2.6及更高版本和Python 3.x:
except Exception as e: print(e)
对于Python 2.5及更早版本,使用:
except Exception,e: print str(e)
我建议使用try-except语句。此外,日志异常不是使用print语句,而是在记录器上记录级别为ERROR的消息,我发现这比print输出更有效。该方法只能从异常处理程序调用,如下所示:
import logging
try:
*code goes here*
except BaseException:
logging.exception("*Error goes here*")
如果你想了解更多关于日志记录和调试的知识,这个python页面上有很好的文档。
如果你想传递错误字符串,这里有一个来自错误和异常(Python 2.6)的例子
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs