通常未处理的异常会转到 stdout(或 stderr?),我正在构建一个应用程序,我想在关闭之前将此信息传递给 GUI 并将其显示给用户,同时我想编写它到一个日志文件。所以,我需要一个包含异常全文的 str。
我该怎么做?
最佳答案
使用 sys.excepthook 替换基本异常处理程序。你可以这样做:
import sys
from PyQt4 import QtGui
import os.path
import traceback
def handle_exception(exc_type, exc_value, exc_traceback):
""" handle all exceptions """
## KeyboardInterrupt is a special case.
## We don't raise the error dialog when it occurs.
if issubclass(exc_type, KeyboardInterrupt):
if QtGui.qApp:
QtGui.qApp.quit()
return
filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
filename = os.path.basename( filename )
error = "%s: %s" % ( exc_type.__name__, exc_value )
QtGui.QMessageBox.critical(None,"Error",
"<html>A critical error has occured.<br/> "
+ "<b>%s</b><br/><br/>" % error
+ "It occurred at <b>line %d</b> of file <b>%s</b>.<br/>" % (line, filename)
+ "</html>")
print "Closed due to an error. This is the full error report:"
print
print "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
sys.exit(1)
# install handler for exceptions
sys.excepthook = handle_exception
这会捕获所有未处理的异常,因此您不需要在代码的顶层使用 try...except block 。
关于Python:如何以替代方式处理任何未处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1235349/