在 ipdb shell 中使用 IPython 魔法函数

27
在使用ipdb my_script.py调试Python脚本时,我想在ipdb调试会话Shell中使用IPython魔术函数,例如%paste%cd。这是否可行以及如何实现?
2个回答

23
根据ipdb Github repo,魔术IPython函数不可用。幸运的是,IPython调试器提供了一些线索,可以在不启动单独的IPython shell的情况下获得此功能。
以下是我运行%cpaste的步骤:
ipdb> from IPython import get_ipython
ipdb> shell = get_ipython()
ipdb> shell.find_line_magic('cpaste')()
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:for i in range(0,5):
:       print i
:--
0
1
2
3
4

通过使用方法find_line_magic(your_magic_function),您可以逐步执行代码并访问所有IPython魔术函数。


1
你能将 ipdb 的上下文(例如本地变量)传递给"cpaste"吗? - toto_tico

19

你可以像pdb一样,在栈内打开IPython shell。请按照以下步骤:

  • 从IPython导入embed(),并将其放置在代码中。
  • 运行脚本

例如:

from IPython import embed

def some_func():
    i = 0
    embed()
    return 0

在 Python shell 中:
>>> te.func()

IPython 1.0.0 -- An enhanced Interactive Python.
(...)

In [1]: %whos

Variable   Type    Data/Info
i          int     0

In [2]:

这是您在寻找的内容吗?


2
我想在我的代码中使用魔术函数,而不导入任何IPython函数。 - Fish Monitor
1
@flebool,如果能够在调试器暂停程序时随时访问魔术函数而无需在程序中编写断点,那将非常方便。 - Fish Monitor
1
提供的答案虽然有效地提供了一种允许通过ipython shell而不是ipdb shell使用魔术函数的方式,但遗憾的是这种方法并不能在ipdb shell中使用。 - Manav Kataria
11
这种方法更加简单。您还可以将这两行代码合并在一起:from IPython import embed; embed(); import ipdb; ipdb.set_trace(),然后您就可以在代码中使用IPython的所有魔术函数了。 - Alan Dong
1
@Curious,您只需退出ipython解释器即可返回到ipdb以便执行该操作。 - alpha_989
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接