所以我正在运行一个Python脚本,在其中我通过编写以下内容来调用Python的调试器PDB:
import ipdb; ipdb.set_trace()
(iPython的PDB版本,尽管就此事而言,我认为它没有什么区别;我仅将它用于彩色输出)。
现在,当我进入调试器时,我想执行多行语句,例如 if 子句或 for 循环,但是一旦我键入
if condition:
并按回车键,我就会收到错误消息 *** SyntaxError : 无效语法(,第 1 行)
如何在 PDB 中执行多行语句?如果不可能,是否有办法解决这个问题,仍然执行 if 子句或 for 循环?
So I am running a Python script within which I am calling Python's debugger, PDB by writing:
import ipdb; ipdb.set_trace()
(iPython's version of PDB, though for the matter I don't think it makes a difference; I use it for the colored output only).
Now, when I get to the debugger I want to execute a multi-line statement such as an if clause or a for loop but as soon as I type
if condition:
and hit the return key, I get the error message *** SyntaxError: invalid syntax (<stdin>, line 1)
How can one execute multi-line statements within PDB? If not possible is there a way around this to still executing an if clause or a for loop?
发布评论
评论(6)
您可以在 pdb 中执行此操作,以启动一个包含所有可用局部变量的临时交互式 Python 会话:
完成后,使用 Ctrl-D 返回到常规 pdb 提示符。
只是不要按 Ctrl-C,这将终止整个 pdb 会话。
You could do this while in pdb to launch a temporary interactive Python session with all the local variables available:
When you're done, use Ctrl-D to return to the regular pdb prompt.
Just don't hit Ctrl-C, that will terminate the entire pdb session.
在 python3
ipdb
(和pdb
)中,有一个名为 互动。它可用于:要使用它,只需在 pdb 提示符下输入
interact
即可。除此之外,它对于应用跨多行的代码以及避免意外触发其他 pdb 命令非常有用。In python3
ipdb
(andpdb
) have a command called interact. It can be used to:To use it, simply enter
interact
at the pdb prompt. Among other things, it's useful for applying code spanning multiple lines, and also for avoiding accidental triggering of other pdb commands.我的建议是使用 IPython 嵌入。
My recommendation is to use IPython embedding.
在 Python (2.7.1) 解释器或调试器 (import pdb) 中,您可以使用以下语法执行多行语句。
注意:当我在解释器中时,我必须按两次 return 才能执行代码。然而,在调试器内,我只需按回车一次。
Inside the Python (2.7.1) interpreter or debugger (import pdb), you can execute a multi-line statement with the following syntax.
Note: When I'm inside the interpreter, I have to hit return twice before the code will execute. Inside the debugger, however, I only have to hit return once.
如果您希望在遇到断点时执行几个命令,则存在特殊情况。然后是调试器命令
commands
。它允许您输入多行命令,然后使用end
关键字结束整个序列。有关(pdb) 帮助命令的更多信息
。There is the special case if you want a couple of commands be executed when hitting a break point. Then there is the debugger command
commands
. It allows you to enter multiple lines of commands and then end the whole sequence with theend
key word. More with(pdb) help commands
.我不知道你是否能做到这一点,但这对于 ipdb 来说是一个很棒的功能。当然,您可以使用列表推导式,并执行简单的多行表达式,例如:
您还可以事先编写一些函数来执行通常需要多行执行的操作。
I don't know if you can do this, that'd be a great feature for ipdb though. You can use list comprehensions of course, and execute simple multi-line expressions like:
You could also write some functions beforehand to do whatever it is you need done that would normally take multiple lines.