可以从代码进入ipython吗?

84 投票
13 回答
24597 浏览
提问于 2025-04-15 12:54

为了调试我的代码,pdb 还不错。不过,如果我能进入 ipython 就会更酷(也更有帮助)了。这个可以做到吗?

13 个回答

12

如果你在使用较新版本的IPython(版本大于0.10.2),你可以试试下面的代码:

from IPython.core.debugger import Pdb
Pdb().set_trace()

不过,直接使用ipdb可能会更好。

59

在IPython 0.11版本中,你可以像这样直接把IPython嵌入到你的代码里。

你的程序可能看起来像这样:

In [5]: cat > tmpf.py
a = 1

from IPython import embed
embed() # drop into an IPython session.
        # Any variables you define or modify here
        # will not affect program execution

c = 2

^D

当你运行这个程序时,会发生这样的事情(我随便选择在一个已经存在的IPython会话中运行它。根据我的经验,这样嵌套IPython会话可能会导致崩溃)。

In [6]:

In [6]: run tmpf.py
Python 2.7.2 (default, Aug 25 2011, 00:06:33)
Type "copyright", "credits" or "license" for more information.

IPython 0.11 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: who
a       embed

In [2]: a
Out[2]: 1

In [3]:
Do you really want to exit ([y]/n)? y


In [7]: who
a       c       embed
117

有一个叫做 ipdb 的项目,它把 iPython 嵌入到了标准的 pdb 中,这样你就可以直接这样做:

import ipdb; ipdb.set_trace()

你可以通过常规的方式安装它,使用 pip install ipdb 命令。

ipdb 的体积很小,所以除了用 easy_install 安装之外,你也可以在你的 Python 路径下创建一个叫 ipdb.py 的文件,然后把以下内容粘贴到这个文件里:

import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi

shell = IPShell(argv=[''])

def set_trace():
    ip = ipapi.get()
    def_colors = ip.options.colors
    Pdb(def_colors).set_trace(sys._getframe().f_back)

撰写回答