如果只有异常时才想要进入调试器,您可以定义一个自定义 excepthook:
import sys
def excepthook(type_, value, tb):
import traceback
import pdb
traceback.print_exception(type_, value, tb)
pdb.post_mortem(tb)
sys.excepthook = excepthook
def main():
message = "hello world"
message[20]
main()
运行该脚本会将您带入pdb,进入引发异常的帧:
% script.py
Traceback (most recent call last):
File "/home/unutbu/pybin/script.py", line 16, in <module>
main()
File "/home/unutbu/pybin/script.py", line 14, in main
message[20]
IndexError: string index out of range
> /home/unutbu/pybin/script.py(14)main()
-> message[20]
(Pdb) p message
'hello world'
(Pdb) p message[20]
*** IndexError: IndexError('string index out of range',)
(Pdb) p len(message)
11
如果定义异常钩子看起来代码太多,你可以将它藏在一个实用模块中,例如utils_debug.py:
import sys
def enable_pdb():
def excepthook(type_, value, tb):
import traceback
import pdb
traceback.print_exception(type_, value, tb)
pdb.post_mortem(tb)
sys.excepthook = excepthook
然后你只需要添加
import utils_debug as UDBG
UDBG.enable_pdb()
到你的script.py
。
或者,如果你正在使用IPython,你可以使用%pdb魔术函数(在异常发生时将你降入ipdb
)。
不清楚为什么在pdb提示符处检查size
会引发NameError。(一个可运行的示例会非常有用。)您可以尝试使用bt
(回溯)来检查帧堆栈。如果size
在不同的帧中定义,而不是pdb
当前所在的帧中,则可能可以使用u
(上移)来到定义size
的帧。