在异常时启动 IPython shell [英] Launch an IPython shell on exception
问题描述
当我的程序运行引发异常的行时,有没有办法启动 IPython shell 或提示?
Is there a way to launch an IPython shell or prompt when my program runs a line that raises an exception?
我最感兴趣的是引发异常的范围(和子范围)中的上下文、变量.类似于 Visual Studio 的调试,当抛出异常但未被任何人捕获时,Visual Studio 将停止并提供调用堆栈和每个级别存在的变量.
I'm mostly interested in the context, variables, in the scope (and subscopes) where the exception was raised. Something like Visual Studio's debugging, when an exception is thrown but not caught by anyone, Visual Studio will halt and give me the call stack and the variables present at every level.
您认为有没有办法使用 IPython 获得类似的东西?
Do you think there's a way to get something similar using IPython?
启动 IPython 时的 -pdb
选项似乎没有做我想要的(或者我可能不知道如何正确使用它,这是完全有可能).我运行以下脚本:
The -pdb
option when launching IPython doesn't seem do what I want (or maybe I don't know how to use it properly, which is entirely possible). I run the following script :
def func():
z = 2
g = 'b'
raise NameError("This error will not be caught, but IPython still"
"won't summon pdb, and I won't be able to consult"
"the z or g variables.")
x = 1
y = 'a'
func()
使用命令:
ipython -pdb exceptionTest.py
当出现错误时停止执行,但给我带来一个 IPython 提示,我可以访问脚本的全局变量,但不能访问函数 func 的局部变量.pdb
仅在我直接在 ipython 中键入导致错误的命令时调用,即 raise NameError("This, sent from IPython prompt, will trigger pdb.")
.
Which stops execution when the error is raised, but brings me an IPython prompt where I have access to the global variables of the script, but not the local variables of function func. pdb
is only invoked when I directly type a command in ipython that causes an error, i.e. raise NameError("This, sent from the IPython prompt, will trigger pdb.")
.
我不一定需要使用 pdb
,我只想访问 func
中的变量.
I don't necessarily need to use pdb
, I'd just like to have access to the variables inside func
.
编辑 2: 已经有一段时间了,IPython 的 -pdb
选项现在可以正常工作了.这意味着当我引发异常时,我可以返回 func
的范围并读取其变量 z
和 g
没有任何问题.即使不设置 -pdb
选项,也可以在交互模式下运行 IPython,然后在程序退出并出现错误后调用魔法函数 %debug
—— 这也会让你掉线进入具有所有范围可访问的交互式 ipdb 提示.
EDIT 2: It has been a while, IPython's -pdb
option is now working just as I want it to. That means when I raise an exception I can go back in the scope of func
and read its variables z
and g
without any problem. Even without setting the -pdb
option, one can run IPython in interactive mode then call the magic function %debug
after the program has exit with error -- that will also drop you into an interactive ipdb prompt with all scopes accessibles.
推荐答案
更新 IPython v0.13:
import sys
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose',
color_scheme='Linux', call_pdb=1)
这篇关于在异常时启动 IPython shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!