So I am attempting to make a module that, when imported, will cause any exception to drop into pdb. I'm thinking it will look something like this:
#file A.py
import pdbOnException
a = 1/0
print a
#file pdbOnException
import sys, pdb
magic_object = # do magic stuff to g开发者_运维知识库et an object that, when called, does what I want :D
try:
magic_object()
except:
tb = sys.exc_info()[2]
pdb.post_mortem(tb)
Hopefully it is fairly obvious what I am trying to do. I am trying to make it so that any module that imports this will have its unhandled exceptions go to pdb.
Edit: I thought I should add what I want to use this for, and see if you know anything about that. I am planning on adding the module to eclipse's "Forced Builtins" so that eclipse will have this functionality (it is SORELY needed) Can anyone help me out?
Edit2: after playing with eclipse a bunch, it looks like there is NO WAY to force eclipse to run a set of code (i.e. like PYTHONSTARTUP) prior to running any code. Which sucks. Therefore I think I will just go for the decorator.
If you still have an idea of how to do this by just importing modules, I am all ears. It could be added to the IDLE startup script.
Update: I just got something working using decorators, but the user has to call it for their main function (which isn't the end of the world... but I would like even more functionality). Here it is:
def pdb_on_exception(function):
def returnfunction(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as E:
traceback.print_tb(sys.exc_info()[2])
print E
tb = sys.exc_info()[2]
pdb.post_mortem(tb)
return returnfunction
This will drop you into pdb if there is an unhandled exception on the function that is being decorated. Which is cool but still not what I want :D
That's pretty trivial, you just hook into sys.excepthook:
fullofeels.py:
import sys, pdb
def except_hook(exctype, value, traceback):
if previous_except_hook:
previous_except_hook(exctype, value, traceback)
pdb.post_mortem(traceback)
previous_except_hook = sys.excepthook
sys.excepthook = except_hook
Usage:
Normally we just get a traceback:
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
But import fullofeels, and we fall into pdb:
>>> import fullofeels
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
> <stdin>(1)<module>()
(Pdb)
Tada!
I have no idea how many eels are in that hovercraft, but for simple cases it works.
精彩评论