编辑
2025-01-24
pytorch
00
请注意,本文编写于 90 天前,最后修改于 90 天前,其中某些信息可能已经过时。

目录

googleColab
控制异常:%xmode
Debugging
Partial list of debugging commands

googleColab

代码开发和数据分析总是需要一些尝试和错误,而 IPython 包含简化这一过程的工具。本节将简要介绍控制 Python 异常报告的一些选项,然后探讨调试代码错误的工具。

参考博客

官方colab使用手册

控制异常:%xmode

%xmode 接收一个参数,即模式,有三种可能:Plain(普通)、Context(上下文)和 Verbose(详细)。默认模式是 Context(上下文),输出结果如图所示。普通模式更简洁,提供的信息更少:

python
%xmode Verbose

Debugging

用于交互式调试的标准 Python 工具是 pdb​,即 Python 调试器。此调试器允许用户逐行遍历代码,以查看可能导致更困难错误的原因。它的 IPython 增强版本是 ipdb,即 IPython 调试器。

有许多方法可以启动和使用这两个调试器;我们不会在这里完全介绍它们。请参阅这两个实用程序的在线文档以了解更多信息。

在 IPython 中,也许最方便的调试界面是 %debug magic 命令。如果你在命中异常后调用它,它会在异常点自动打开一个交互式调试提示。ipdb 提示符可让您浏览堆栈的当前状态、探索可用变量,甚至运行 Python 命令!

python
%debug
python
> <ipython-input-1-d849e34d61fb>(2)func1() 1 def func1(a, b): ----> 2 return a / b 3 ipdb> print(a) 1 ipdb> print(b) 0 ipdb> quit

这使我们不仅可以快速找出导致错误的原因,还可以快速找出导致错误的函数调用。如果希望调试器在引发异常时自动启动,则可以使用 %pdb magic 函数来启用此自动行为:

shell
%xmode Plain %pdb on func2(1)

交互式调试器的功能远不止这些--我们甚至可以在堆栈中上下移动,并探索其中的变量值:

shell
> <ipython-input-1-d849e34d61fb>(2)func1() 1 def func1(a, b): ----> 2 return a / b 3 ipdb> up > <ipython-input-1-d849e34d61fb>(7)func2() 5 a = x 6 b = x - 1 ----> 7 return func1(a, b) ipdb> print(x) 1 ipdb> up > <ipython-input-6-b2e110f6fc8f>(1)<module>() ----> 1 func2(1) ipdb> down > <ipython-input-1-d849e34d61fb>(7)func2() 5 a = x 6 b = x - 1 ----> 7 return func1(a, b) ipdb> quit

这不仅能让我们快速找出导致错误的原因,还能找出导致错误的函数调用。 如果希望调试器在出现异常时自动启动,可以使用 %pdb 神奇函数来打开这种自动行为:

python
%xmode Plain %pdb on func2(1)
python
Exception reporting mode: Plain Automatic pdb calling has been turned ON Traceback (most recent call last): File "<ipython-input-9-569a67d2d312>", line 3, in <module> func2(1) 1 frames File "<ipython-input-1-d849e34d61fb>", line 2, in func1 return a / b ZeroDivisionError: division by zero > <ipython-input-1-d849e34d61fb>(2)func1() 1 def func1(a, b): ----> 2 return a / b 3 ipdb> print(b) 0 ipdb> quit

Partial list of debugging commands

部分调试命令列表

There are many more available commands for interactive debugging than I've shown here. The following table contains a description of some of the more common and useful ones:

markdown
Command Description l(ist) Show the current location in the file h(elp) Show a list of commands, or find help on a specific command q(uit) Quit the debugger and the program c(ontinue) Quit the debugger, continue in the program n(ext) Go to the next step of the program <enter> Repeat the previous command p(rint) Print variables s(tep) Step into a subroutine r(eturn) Return out of a subroutine

For more information, use the help command in the debugger, or take a look at ipdb's online documentation.

本文作者:wenY

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!