473,614 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(ty pe, value, tb):
import traceback
rawreport = traceback.forma t_exception(typ e, value, tb)
report = '\n'.join(rawre port)
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 4434

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(ty pe, value, tb):
import traceback
rawreport = traceback.forma t_exception(typ e, value, tb)
report = '\n'.join(rawre port)
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.except hook = 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.except hook =
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
2265
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 some methods to use on it. >From what I can tell the traceback that's passed in works differently from the module traceback. I just need to get the traceback to log it. I can use type and value,
2
3510
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
2244
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, there are many calls to stderr that are made which gives this kind of result: Traceback (most recent call last): File "C:\somefolder\logger.py", line 711, in onTimer a.index('notinlist')
1
7965
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 implements a method for allowing external method/classes to get a connection from that pool. he main issue is that, from a testing app, I create a loop like this to test the pool: import thread
1
2219
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 sys.excepthook=myexcepthook rest of script.... (now protected by catchall exception hook)
0
1139
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" processes. I'm doing some testing with Python 2.5b2 and can't seem to get it to work properly. Here is a very small script that I think should work but doesn't. import sys
5
3654
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 systems there might not be any command window or terminal window to show the traceback messages in). Do I want to do something like override the print_exc (or format_exc?) method of traceback to get the text of the message and call my dialog box...
1
1925
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
2144
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: ----------------------------------------------------------------------- import sys
0
8198
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8591
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8444
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7115
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6093
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5549
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4058
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4138
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.