通常未处理的异常到标准输出(或标准错误?),我建立一个应用程序,我想在关闭前通过这一信息的GUI,并显示给用户,并在同一时间,我想将它写入日志文件.所以,我需要一个带有异常全文的str.
我怎样才能做到这一点?
Nei*_*eil 18
使用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
Run Code Online (Sandbox Code Playgroud)
这会捕获所有未处理的异常,因此您不需要尝试...除了代码顶层的块.
你已经得到了很好的答案,我只想再添加一个多年来以多种语言为我提供的针对特定问题"如何干净地诊断,记录等out of memory错误?"的提示.问题是,如果你的代码在足够的对象被销毁并且它们的内存被回收之前得到控制,那么内存可能太紧,无法进行属性记录,gui工作等等 - 我们如何确保不会发生这种情况?
答:建立紧急藏匿,以便您知道可以在紧急情况下使用它:
rainydayfund = [[] for x in xrange(16*1024)] # or however much you need
def handle_exception(e):
global rainydayfund
del rainydayfund
... etc, etc ...
Run Code Online (Sandbox Code Playgroud)
try:
# blah blah The Main Loop, function, whatever...
except e:
do_something_with(str(e))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8341 次 |
| 最近记录: |