Problem overriding sys.excepthook

Patrick Maupin pmaupin at gmail.com
Sun Jan 1 17:51:44 EST 2006


Lunchtimemama wrote:
> Yo all, I'm getting into Python for the first time and I'm really
> having a blast. I've hit a bit of a snag and was wondering if someone
> could lend some insight. Here be the code:
>
> import sys
> def myexcepthook(type, value, tb):
>   import traceback
>   rawreport = traceback.format_exception(type, value, tb)
>   report = '\n'.join(rawreport)
>   errorlog = open('error.log','a')
>   errorlog.write(('%s\n' + '-'*30 + '\n\n') % report)
>   errorlog.close()
> sys.excepthook = myexcepthook
>
> Now here's the trouble: if I enter that line-by-line into the
> interpreter in interactive mode, the custom exception hook will handle
> all exceptions, but if I put that in a script that I run from the
> shell, it only catches some exceptions. For example, it would catch an
> undefined name, like if I just put:
>
> spam
>
> into the program above, the override would work. But if I made a
> syntactical error, like:
>
> 1 = spam
>
> then it would fall to the standard sys.excepthook. Is there some lazy
> evaluation that I don't know about? I'm on Windows, if that makes a
> difference. Thank for the help.
>

Python first compiles, then executes.  However, since an "import" is
considered to be an execution, you can retrieve this sort of
compile-time error, but only on modules which are imported _after_ you
hook the exception handler.

HTH,
Pat




More information about the Python-list mailing list