为ipdb获取IPython的补全功能

24 投票
6 回答
7083 浏览
提问于 2025-04-17 17:21

我安装了 IPython(0.13.1)ipdb(0.7),然后在我的脚本里插入了这一行 import ipdb;ipdb.set_trace(),接着运行了 python my_script.py。现在我在 ipdb 的提示符下,虽然可以用按下 Tab 键来自动补全一些内容,但这和在 IPython 里得到的自动补全不太一样。在 ipdb 提示符下输入 requests. 然后按 <tab>(在导入之后)并不会像在 IPython 中那样给我列出属性。我该怎么才能在 ipdb 中得到和 IPython 一样的 Tab 补全呢?

顺便说一下,当我运行 python -m ipdb my_script.py 时,Tab 补全的功能和 IPython 一样好,但这样做的缺点是它会从第一行开始调试,而不是从我插入 import ipdb;ipdb.set_trace() 的那一行开始。

6 个回答

3

使用 easy_install readline 有帮助吗?

4

我也遇到过同样的问题,我是这样解决的:

sudo pip install --upgrade ipdb ipython readline

如果你没有安装 readline,记得按照 @musashi14 的建议安装 libncurses5-dev

6

我在我的Mac上也遇到了同样的问题,使用的是 ipython==0.13.2ipdb==0.7,在一个 Python 2.7.5 的虚拟环境里。当我尝试调试时,虽然可以使用Tab键补全内置函数,但却无法补全当前作用域中的变量。我发现我在家目录下有一个自定义的 .pdbrc 文件(可以参考这个链接:http://docs.python.org/2/library/pdb.html#id2)。在我把文件里的内容都注释掉后,Tab键补全又可以用了。

我不知道我是什么时候和为什么添加了这个文件,但里面的内容是这样的:

# See http://docs.python.org/2/library/pdb.html#id2 for the structure of this file.
import pdb

# 'inspect x' will print the source code for a method, class or function.
alias inspect import inspect;print inspect.getsource(%1)
alias i import inspect;print inspect.getsource(%1)
# 'help x' opens the man-style help viewer from the interpretter on an object
alias help !print help(%1)
alias h !print help(%1)
# For ordinary Python objects, ppo will pretty-print members and their values.
alias ppo pp %1.__dict__
# ppio runs ppo over a sequence of objects
alias ppio pp [a.__dict__ for a in %1]

# This tries to enable tab-completion of some identifiers.
!import rlcompleter
!pdb.Pdb.complete = rlcompleter.Completer(locals()).complete

# Taken from https://gist.github.com/1125049
# There are a couple of edge cases where you can lose terminal
# echo. This should restore it next time you open a pdb.
!import termios, sys
!termios_fd = sys.stdin.fileno()
!termios_echo = termios.tcgetattr(termios_fd)
!termios_echo[3] = termios_echo[3] | termios.ECHO
!termios_result = termios.tcsetattr(termios_fd, termios.TCSADRAIN, termios_echo)

还需要进一步研究,看看是什么导致了那里的Tab补全失效...

撰写回答