Problem overriding sys.excepthook
pmaupin at gmail.com
Sun Jan 1 23:24:38 EST 2006
> Forgive my ignorance, but I'm not quite sure what you mean. I tried
> importing the traceback module at the beginning of the script, but that
> didn't make a difference. Could you provide example code to illustrate
> your comment? Thanks.
Assume your main module has your exception hook code in it, up to and
including the line "sys.excepthook = myexcepthook".
As you have noticed, "1 = spam" in your main module would cause an
uncaught exception. This is because this exception is raised during
the compilation phase of the module, before you hooked the exception
vector. This is true NO MATTER WHERE in the main module this statement
is -- Python will compile the entire module before executing it.
Now assume that the statement "1 = spam" is in module "foo.py" instead
of in your main module. If you "import foo" at the top of your main
module, you will have the same result but for slightly different
reasons-- foo.py will be compiled during execution of the main module's
"import" statement (although AFTER compilation of the main module), so
the exception will still be raised before you have assigned your
HOWEVER, if you "import foo" AFTER the line "sys.excepthook =
myexcepthook", then the compilation of foo.py will occur after your
exception hook has been set, and your exception handler will execute on
the syntax error "1 = spam" inside foo.py.
So the bottom line is that you can't log syntax errors for your main
module, but you _can_ log syntax errors for other modules which your
main module imports.
I think one of the reasons you are confused is that the interactive
mode, by necessity, has to compile incrementally. But compilation of
imported modules, and compilation of a main module in non-interactive
mode, occurs before any code in that particular module is executed.
Please let me know if it's still unclear.
More information about the Python-list