473,394 Members | 1,481 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Problem overriding sys.excepthook

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.

-LTM

Jan 1 '06 #1
6 4406

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

Jan 1 '06 #2
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.

-LTM

Jan 2 '06 #3
Lunchtimemama wrote:
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
exception hook.

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.

Regards,
Pat

Jan 2 '06 #4
Thank you for a fine explanation Pat, that clears things up very
nicely. I have one remaining question which I imagine amounts to taste.
What is the superior method of exception handling:

A) To, as you suggest above, import the code as a module from within a
program with special exception handling code.

or

B) To pipe sys.stderr to a file and keep the OS on the lookout for a
non-zero errorlevel (via a batch file or some such) and then launch
another Python script to further handle the error output.

My goal is to upload error reports to a server. My criteria for
preference are first performance and second conformance with Python
style. Any overwhelming opinion or alternative solution? Thanks again.

Jan 2 '06 #5
Lunchtimemama wrote:
What is the superior method of exception handling:

....

For a start, note that the exception hook does not _really_ have to be
in the main module, just imported before any "protected" code is to be
executed.

Having said that, what I personally typically do for exception trapping
doesn't even require an exception hook. I will execute all my code
from inside a try/except block in the main module. If the exception is
invoked, you can query and get all the data about the exception like
you are currently doing, and then re-raise the exception (or not).

I haven't given too much thought to when I would set an exception hook.
It seems like more of a debugger kind of thing. Especially if you
have control over the entire app, a try/except at the top level feels
cleaner to me.

Regards,
Pat

Jan 3 '06 #6
Try/except sounds like the way to go. Thanks.

Jan 3 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Josh Close | last post by:
When sys.excepthook is called, type, value and traceback are passed into it. How do I get the values of traceback? I've tried printing it, but I get the memory location. I'm gussing there are...
2
by: callmebill | last post by:
I'm having a tough time figuring this one out: class MyKBInterrupt( ..... ): print "Are you sure you want to do that?" if __name__ == "__main__": while 1: print "Still here..."
2
by: Kreedz | last post by:
Hi, I'm making some intelligent logging module that redirects stdout and stderr of a wxPython GUI. I am logging the exceptions in a wx TreeCtrl. My problem is that when an exception is thrown,...
1
by: Jesus Rivero - (Neurogeek) | last post by:
Hello guys, I have this problem and i don't know any workarounds yet. Im implementing a DB Connection pool, which initially creates 20 connections and keep them in a dictionary. It also...
1
by: Hari Sekhon | last post by:
I've written an except hook into a script as shown below which works well for the most part and catches exceptions. import sys def myexcepthook(type,value,tb): do something ...
0
by: Larry Bates | last post by:
I have some classes that trap hook sys.excepthook and log exceptions prior to the program exiting. This has proven to be an effective way to log what is going on with many of my "lights out"...
5
by: Bob Greschke | last post by:
I want to cause any traceback output from my applications to show up in one of my dialog boxes, instead of in the command or terminal window (between running on Solaris, Linux, OSX and Windows...
1
by: ian | last post by:
Hi, sys.excepthook don't work if an exception come in a thread... It's normal or its a bug ? There are any tip ? look here : http://spyced.blogspot.com/2005_06_01_archive.html Thx
3
by: Sami | last post by:
Hello, I am new to Python. I tried to hook my own ExceptionPrintingFunction sys.excepthook but it does not work. This is what I wrote:...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.