调试器

调试 在Spyder中通过与增强的 ipdb 中的调试器 IPython控制台 。这允许直接从Spyder GUI以及所有熟悉的IPython控制台命令查看和控制断点和执行流。

A Spyder IPython console window, showing the ipdb debugger in action

使用ipdb调试

控件完全控制调试器的执行。 Debug 菜单, Debug toolbar 并通过可配置的键盘快捷键以及标准 ipdb console commands

A Spyder IPython console window, showing debugging from toolbar

此外, 编辑 用箭头显示调试器当前停止的代码行。

Spyder Editor showing the debugging panel

Spyder的调试器提供语法突出显示、代码完成和命令历史记录,其工作方式与普通交互式解释器完全相同。

使用向上和向下箭头重新调用以前的命令,然后按 Tab 若要触发自动完成建议,请执行以下操作。

A Spyder IPython console window, showing autocompletion when debugging

此外,IPython的 magic functions 在调试模式下可用。例如,您可以运行 %ls 要列出当前工作目录的内容,请执行以下操作 %timeit 来检查给定的代码片段有多快。

Ipython console in debug mode showing timeit magic

最后,您可以在Spyder的调试器中输入和执行多行语句,就像使用常规的IPython提示符一样,以便轻松运行复杂的代码。

Debugger showing multiline debugger

断点

Spyder's debugger is integrated with the Breakpoints pane, which lists the file, line, and condition (if any) of every breakpoint defined. To open it, select Debug ‣ List breakpoints, or press Ctrl-Shift-B (Cmd-Shift-B on macOS).

Spyder's Breakpoints panel, with a number of examples showing file, line number and an optional condition

设置和清除断点有几种不同的方法:

  • 使用 Set/clear breakpoint 选项。

  • 通过按下可配置键盘快捷键 (F12 表示正常,或 Shift-F12 默认情况下用于条件断点)。

  • 通过单击编辑器中打开的文件中的行号左侧(添加 Shift 用于条件断点)。

  • 使用 breakpoint() 代码中的内置函数。

  • 以交互方式,使用 b 调试会话中的命令。

Spyder showing setting conditional breakpoint

方法访问和编辑每个断点处的局部变量和全局变量。 变量资源管理器

Spyder's console and variable explorer showing local and global variables when debugging

高级功能

通过启用新的 Ignore Python libraries while debugging Spyder首选项中的选项,位于 IPython Console ‣ Debugger ‣ Debug 。这将跳过您已安装的所有内置和第三方Python模块。

Spyder's preferences showing Ignore Python libraries while debugging options

如果您的代码具有与PDB命令同名的变量(例如 bstep ),您在调试时仍然可以正常引用它们。要调用相应的PDB命令,只需在其前面添加一个感叹号(例如 !b!step )。

Spyder's IPython console showing Pdb commands

您可以让Spyder在每次调试器停止时自动执行自定义代码段。例如,您可以使用它来设置特定变量,或者导入常用模块,以便它们在调试时始终可用。要设置此设置,请转到 Preferences ‣ IPython Console ‣ Debugger ‣ Run code while debugging ,然后输入要在每个步骤中执行的代码。

Spyder's preferenes with debugging snippet

Matplotlib支持

Generating Matplotlib figures is fully supported while the debugger is active, including all the different graphics backends. Use the %matplotlib magic to change to an interactive backend (e.g. %matplotlib qt5) to pan, zoom and adjust your plots in a separate window, or switch back to the default inline (%matplotlib inline) to see them displayed right in the 地块 pane.

Debugger showing matplotlib interactive backend

要避免在调试时显示绘图,请停用 Process execute events while debugging 选项输入 Preferences ‣ IPython console ‣ Debugger