Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python - Get last exception in pdb

Is there a way to examine the last exception when in pdb/before entering pdb? (Using python 2.7.5).

Immediately (yes, I enter no other commands at all) after an exception being raised in my code, I do sys.exc_info(); this just results in (None, None, None). At this point, I can do pdb.pm(), and pdb starts at the point that the exception is raised.

I'd like to be able to examine this exception object (it is not stored in a variable before being raised).

There is nothing obviously helpful in http://docs.python.org/2/library/pdb.html or http://docs.python.org/2/library/sys.html

Edit: I know about set_trace. I'd like to examine the exception before I modify the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is this what you are looking for?

import pdb
try:
    1/0
except Exception as err:
    pdb.set_trace()

% test.py
--Return--
> /home/unutbu/pybin/test.py(8)<module>()->None
-> pdb.set_trace()
(Pdb) err
ZeroDivisionError('integer division or modulo by zero',)
(Pdb) quit

If you do not want to modify the code where the exception originates, you could instead redefine sys.excepthook:

import pdb
import sys
def excepthook(type, value, traceback):
    pdb.set_trace()
sys.excepthook = excepthook

1/0

% test.py
--Return--
> /home/unutbu/pybin/test.py(7)excepthook()->None
-> pdb.set_trace()
(Pdb) type
<type 'exceptions.ZeroDivisionError'>
(Pdb) value
ZeroDivisionError('integer division or modulo by zero',)
(Pdb) traceback
<traceback object at 0xb774f52c>
(Pdb) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...