Supressing the Windows Error Report MessageBox with Subprocess and Ctypes

Suppressing The Windows Error Report MessageBox With Subprocess And Ctypes

Hands up, anyone who’s written a Python script that was supposed to run for a long period of time unattended on a Windows box, only to come in the next morning to see this kind of dialog box on their screen 5% of the way through?
You wrote your script to handle failures of subprograms, but instead it got stuck waiting for a user to push a button before it would continue. [I can’t convince typepad to display the full-size image, but it’s the ubiquitous Windows crash notification dialog box that makes sense for graphical apps, but not for command-line ones.  Click on the graphic if you want to see the original].
This is an easy four line fix in Python, as long as you’re either using Python 2.5, or have ctypes installed.
At some point in your program’s initialization state, state that you don’t want the process to put up the crash notification dialog:

        if sys.platform.startswith("win"):
            # Don't display the Windows GPF dialog if the invoked program dies.
            # See comp.os.ms-windows.programmer.win32
            #  How to suppress crash notification dialog?, Jan 14,2004 -
	    #     Raymond Chen's response [1]
	    
            import ctypes
            SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN
            ctypes.windll.kernel32.SetErrorMode(SEM_NOGPFAULTERRORBOX);
            subprocess_flags = CREATE_NO_WINDOW
        else:
            subprocess_flags = 0

Now when you launch your sub-processes, make sure on Windows that you don’t ‘or’ the CREATE_DEFAULT_ERROR_MODE flag in, or the subprocess will put up the notification dialog if it crashes.

        import subprocess
        subprc = subprocess.Popen(self._cmd,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT,
                                  shell=True,
                                  cwd=self._cwd,
                                  universal_newlines=True,
                                  creationflags=subprocess_flags)

[1] Reference: http://groups.google.com/group/comp.os.ms-windows.programmer.win32/tree/browse_frm/thread/eeade5ecfa04d000/658b412a62ef5d7a?hl=en&rnum=1
(http://tinyurl.com/2cycse for the full tree-view)
Title photo courtesy of Joey Banks on Unsplash.

Recent Posts

Scroll to Top