如何从wxPython应用程序捕获所有异常? [英] How can I capture all exceptions from a wxPython application?

查看:271
本文介绍了如何从wxPython应用程序捕获所有异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们开发的一些套件编写一个调试应用程序,我想将其推送给几个用户,看看它们是否可以引发任何崩溃。有没有人知道有效地包装wxPython应用程序来捕获任何和所有未处理的异常,导致应用程序崩溃?

I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?

理想情况下,我想要捕获所有输出(不只是错误)并将其记录到文件。任何未处理的异常应该记录到当前文件,然后允许异常按照常规传递(即记录过程应该是透明的)。

Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).

我是确定有人必须在以前做过这些行,但是我还没有设法通过google看起来很有用的东西。

I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.

推荐答案

p>对于记录标准输出,您可以使用stdout包装器,例如这样一个:

For logging standard output, you can use a stdout wrapper, such as this one:

from __future__ import with_statement

class OutWrapper(object):
    def __init__(self, realOutput, logFileName):
        self._realOutput = realOutput
        self._logFileName = logFileName

    def _log(self, text):
        with open(self._logFileName, 'a') as logFile:
            logFile.write(text)

    def write(self, text):
        self._log(text)
        self._realOutput.write(text)

然后你必须initia把它放在你的主要Python文件(运行所有东西的文件)中:

You then have to initialize it in your main Python file (the one that runs everything):

import sys    
sys.stdout = OutWrapper(sys.stdout, r'c:\temp\log.txt')

至于记录异常,最简单的做法是将wx.App的 MainLoop 方法包装在try..except中,然后提取异常信息,以某种方式保存,然后通过 raise 重新提出异常,例如:

As to logging exceptions, the easiest thing to do is to wrap MainLoop method of wx.App in a try..except, then extract the exception information, save it in some way, and then re-raise the exception through raise, e.g.:

try:
    app.MainLoop()
except:
    exc_info = sys.exc_info()
    saveExcInfo(exc_info) # this method you have to write yourself
    raise

这篇关于如何从wxPython应用程序捕获所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆