My sys.excepthook dies painfully

Chris Angelico rosuav at gmail.com
Wed Jul 23 21:50:47 EDT 2014


On Thu, Jul 24, 2014 at 11:30 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> However, I think I have a glimmer of an idea for how the global variable
> might be set to None. When the Python interpreter shuts down, it sets
> global variables to None in some arbitrary order. If the excepthook
> function isn't called until after the shutdown process begins, then
> depending on the phase of the moon, it's possible that ``mylogger`` may
> have been set to None by the time it is called.

In other words, the problem changed when you added the NameError
trigger at the bottom of the script?

Would it be possible to snapshot all critical globals with a closure,
to force them to be held? Something like:

def handler_gen(mylogger, sys):
    def my_error_handler(type, value, tb):
        msg = "Uncaught %s: %s" % (type, value)
        mylogger.exception(msg)
        sys.__excepthook__(type, value, tb)  # print the traceback to stderr

# Install exception handler.
mylogger.info('installing error handler')
sys.excepthook = handler_gen(mylogger, sys)

It seems crazy, but it might work. It's a guaranteed one-way
connection, saying "this function NEEDS these objects".

ChrisA



More information about the Python-list mailing list