[issue11705] sys.excepthook doesn't work in imported modules

STINNER Victor report at bugs.python.org
Fri Apr 1 19:28:33 CEST 2011


STINNER Victor <victor.stinner at haypocalc.com> added the comment:

python -c "import loggingTest" calls PyRun_SimpleStringFlags(). python import_loggingTest.py (import_loggingTest.py just contains "import loggingTest") calls PyRun_SimpleFileExFlags(). Both functions calls PyErr_Print() on error.

An error occurs ("raise Exception" in loggingTest.py) while importing the module, in PyImport_ExecCodeModuleEx().

The real problem is that the module is cleared because it raised an error. Extract of PyImport_ExecCodeModuleEx:

    v = PyEval_EvalCode((PyCodeObject *)co, d, d);
    if (v == NULL)
        goto error;
    ...
  error:
    remove_module(name);

(remove_module() does something like del sys.modules['loggingTest']: because there is only once reference, the destructor of the module is called)

--

You can workaround this corner case by keeping a reference to all used objects using a closure:

-----------
def create_closure(logger, print_exception):
    def handleException(excType, excValue, traceback):
            print_exception(excType, excValue, traceback)
            print "inside exception handler: logger = %s" % logger
            logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
    return handleException

sys.excepthook = create_closure(logger, tb.print_exception)
-----------

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11705>
_______________________________________


More information about the Python-bugs-list mailing list