对于我的调试需求,pdb
还算不错。但是,如果可以的话,它会更酷(并且很有帮助)ipython
。这可能吗?
Answers:
有一个ipdb
项目将iPython嵌入到标准pdb中,因此您可以执行以下操作:
import ipdb; ipdb.set_trace()
可通过通常的方式安装pip install ipdb
。
ipdb
非常短,因此除了easy_installing之外,您还可以ipdb.py
在Python路径上的某个位置创建一个文件,并将以下内容粘贴到该文件中:
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)
ModuleNotFoundError: No module named 'IPython.Debugger'
,ModuleNotFoundError: No module named 'IPython.Shell'
和ImportError: cannot import name 'ipapi'
ModuleNotFoundError: No module named 'IPython.Debugger'
,ModuleNotFoundError: No module named 'IPython.Shell'
和ImportError: cannot import name 'ipapi'
breakpoint()
函数进入ipdb的方法。
在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
def f() : pass ; IPython.embed = f
该embed()
调用为noop,则按Ctrl + D
看起来模块最近已经改头换面了。在IPython 0.13.1上,以下对我有用
from IPython.core.debugger import Tracer; breakpoint = Tracer()
breakpoint() # <= wherever you want to set the breakpoint
虽然可惜,但在qtconsole中这一切都一文不值。
较新的IPython版本提供了一种将IPython会话嵌入和嵌套到任何Python程序中的简便机制。您可以按照以下食谱来嵌入IPython会话:
try:
get_ipython
except NameError:
banner=exit_msg=''
else:
banner = '*** Nested interpreter ***'
exit_msg = '*** Back in main IPython ***'
# First import the embed function
from IPython.frontend.terminal.embed import InteractiveShellEmbed
# Now create the IPython shell instance. Put ipshell() anywhere in your code
# where you want it to open.
ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
然后使用 ipshell()
只要您想放入IPython Shell中就可以使用。这将允许您在代码中嵌入(甚至嵌套)IPython解释器。
快速简便的方法:
from IPython.Debugger import Tracer
debug = Tracer()
然后写
debug()
您想开始调试程序的任何地方。
ImportError: No module named 'IPython.Debugger'
在python 3.4 / IPython 3上
如果最近几天我不得不用谷歌搜索一下,以便添加一个答案...有时能够正常运行脚本,并且仅在出现错误时放入ipython / ipdb中,而不必ipdb.set_trace()
在代码中放入断点是一件很不错的事情
ipython --pdb -c "%run path/to/my/script.py --with-args here"
(第一pip install ipython
和pip install ipdb
当然)
ipython --pdb -- ./path/to/my/script --with-args here
为了使用终端颜色获得IPython的REPL,我必须这样做:
from IPython import start_ipython
start_ipython()
https://ipython.readthedocs.io/zh-CN/stable/api/genic/IPython.html#IPython.start_ipython