我的 Python 脚本崩溃了。为了调试它,我以交互模式运行它 python -i example.py
Traceback (most recent call last):
File "example.py", line 5, in <module>
main()
File "example.py", line 3, in main
message[20]
IndexError: string index out of range
此时,我想检查变量message
。我试过了
>>> message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'message' is not defined
唉 message
不在范围内(尽管 main
是)。这很令人沮丧。如何检查变量?是否有更有用的 python -i
版本可以保留崩溃时的范围(而不是顶级)?
用于上述example.py
的代码。不用说,这是一种简化。
def main():
message = "hello world"
message[20]
main()
最佳答案
要放到调试器只有在出现异常时你可以定义一个custom 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
如果定义异常钩子(Hook)看起来代码太多,你可以把它藏在一个 实用模块,例如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 magic function (当出现异常时,它会将您放入 ipdb
中)。
目前尚不清楚为什么在 pdb 提示符下检查 size
会出现 NameError。 (一个可运行的示例会非常有用。)您可以尝试使用 bt
(backtrace)检查帧堆栈。如果 size
定义在与当前 pdb
不同的框架中,您可以使用 u
(up)到定义 size
的框架。
关于python - Traceback 后如何检查变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22441139/