How can I capture all exceptions from a wxPython application?

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).

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.

Asked by: Sophia794 | Posted: 06-10-2021

Answer 1

For the exception handling, assuming your log file is opened as log:

import sys
import traceback

def excepthook(type, value, tb):
    message = 'Uncaught exception:\n'
    message += ''.join(traceback.format_exception(type, value, tb))

sys.excepthook = excepthook

Answered by: Andrew304 | Posted: 07-11-2021

Answer 2

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:

    def write(self, text):

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')

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.:

    exc_info = sys.exc_info()
    saveExcInfo(exc_info) # this method you have to write yourself

Answered by: Steven646 | Posted: 07-11-2021

Answer 3

You can use


(see Python docs)

and assign some custom object to it, that would catch all exceptions not caught earlier in your code. You can then log any message to any file you wish, together with traceback and do whatever you like with the exception (reraise it, display error message and allow user to continue using your app etc).

As for logging stdout - the best way for me was to write something similar to DzinX's OutWrapper.

If you're at debugging stage, consider flushing your log files after each entry. This harms performance a lot, but if you manage to cause segfault in some underlying C code, your logs won't mislead you.

Answered by: Sydney897 | Posted: 07-11-2021

Answer 4

There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk.

A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:

void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent& event) const
        wxAppConsole::HandleEvent(handler, func, event);
    catch (const std::exception& e)
        wxMessageBox(std2wx(e.what()), _("Unhandled Error"),
            wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));

It's a C++ example, but you can surely translate to Python easily.

Answered by: Sienna347 | Posted: 07-11-2021

Similar questions

How to display Python web application exceptions in PHP-like manner

In this project I must use Python for a website, I'm looking for the errors to go in my browser instead of getting a 500 page. Any tip ? Addition I'm just using plain CGI nothing fancy I tried this as explained here but it does not work #!/usr/bin/env python print "Content-Type: text/plain" print import sys sy...

java - Py4j Exceptions when running application in a server

I have created an application using py4j that makes it possible to save data from python in to SQL database using a java application,everything works so fine when i run the JVM as an application and it actually saves the data. But when i run the code in a server it gives me back an exception.Therfore i thought maybe my server(Wildfly) and Py4j are using the same port so i changed the default py4j port as the turotial sugge...

python - How to catch exceptions in the main that are raised while running PyQt application?

Suppose we have this simple main program: from matplotlib.backends.qt_compat import QtWidgets from initial import InitialWindow if __name__ == '__main__': try: app = QtWidgets.QApplication([]) ex = InitialWindow() app.exec_() except: # Do something print('Hello') The application being run is pretty complex, and there are se...

python - Catching all exceptions in order to debug more easily once my application is deployed

Novice programmer here. I'm phrasing this question in terms of Python, but I think it makes sense for any programming language that has the concept of Exception Handling. Here it is: I'm writing a software for a business client, who will interact with the software by using a GUI. I'm thinking about putting all of the core business logic in a try/except block in order to catch all e...

Else clause application in python exceptions handling

For handling exceptions in python we use this pattern: try: # do something except NameError: # Do something for NameError exceptions except: # Do something for other exceptions raise else: # Do something when didn't exist any exception finally: # Do something whether an exception has occurred or not #rest of codes My question is: What is th...

python - Long chain of exceptions in scrapy splash application

My scrapy application is outputting this long chain of exceptions and I am failing to see what the issue is and the last one has me especially confused. Before I explain why here is the chain: 2020-11-04 17:38:58,394:ERROR:Error while obtaining start requests Traceback (most recent call last): File "C:\Users\lguarro\Anaconda3\envs\virtual_workspace\lib\site-packages\urllib3\

python - Best strategy to avoid exceptions crashing a pyqt application?

This question already has answers here:

python - Why won't Django 1.0 admin application work?

I've just started playing with Django and am loosely following the tutorial with my own set of basic requirements. The models I've sketched out so far are a lot more comprehensive than the tutorial, but they compile fine. Otherwise, everything should have been the same. My problem is with the admin application. I can log into it, and view the editable models, but when I click on a model or any of the change/add but...

python - What is the best way to serve static web pages from within a Django application?

I am building a relatively simple Django application and apart from the main page where most of the dynamic parts of the application are, there are a few pages that I will need that will not be dynamic at all (About, FAQ, etc.). What is the best way to integrate these into Django, idealing still using the Djang...

networking - Embedding a remote Python shell in an application

You can embed the IPython shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recom...

python - Debug Pylons application through Eclipse

I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?

naming - Deploying a python application with shared package

I'm thinking how to arrange a deployed python application which will have a Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in A library installed to wherever the current site-packages directory is. Now, currently, I have the following directory structure in my sources: foo/ ... which...

deployment - How do I deploy a Python desktop application?

I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it. I have no knowledge of deploying "real-life" Python applications, though I have used py2exe in the past with varied success. How would I obfu...

Starting a new database driven python web application would you use a javascript widget framework? If so which framework?

I am starting a new web application project. I want to use python as I am using it at my bread-and-butter-job. However I don't want to reinvent the wheel. Some things I have thought about: AJAX would be nice if it’s not too much of a hazzle. It is best if the licensing allows commercialization but is not crucial at this point. It could also be funny to try out the G...

console application - using curses with raw_input in python

In my python linux console application I use curses to handle displaying of data. At the same time I'd like to have an input line to enter commands, pretty much in good ol' irssi-style. With default curses getch() I'd have to do a lot of coding just to get the basic funcionality of raw_input function - arrow keys to move cursor / browse through the input history. Is there a simple way to get such behavior working w...

scripting - How can I launch an instance of an application using Python?

I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?

Global hotkey for Python application in Gnome

I would like to assign a global hotkey to my Python application, running in Gnome. How do I do that? All I can find are two year old posts saying, well, pretty much nothing :-)

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python