python - JupyterLab 中的 pdb 未进入交互模式

标签 python jupyter-notebook jupyter pdb

我的目标是在 JupyterLab 中使用 pdbipdb 运行一些 python 脚本来捕获我的调试历史。

我首先在我的 python 脚本中插入了 set_trace():

import torch
from IPython.core.debugger import set_trace

def train_batch(model_instance, inputs_source, labels_source, inputs_target, optimizer, args):
    inputs = torch.cat((inputs_source, inputs_target), dim=0)
    total_loss, train_stats = model_instance.get_loss(inputs, labels_source)
    total_loss[args.train_loss].backward()

    set_trace() # insert breakpoint

    optimizer.step()
    return train_stats

然后我在我的 JupyterLab 中运行这个脚本:

!python ./trainer/train.py \
    --base_config ./config/sgd_vannila_0.001.yml \
    --dataset Office-Home \
    --class_num 50 \
    --src_address ./data/office-home/Art.txt \
    --tgt_address ./data/office-home/Clipart.txt \
    --name transfer.debug.rand_noise \
    --train_steps 10000 \
    --seed 2 \
    --filter_classes=0,50 \
    --eval_interval 50

执行在断点处停止,但不提供交互框来提示任何ipdb 指令。 pdb 或 jupyter notebook 也是如此。

enter image description here


我尝试过的事情:

  • 重新启动 Chrome 浏览器或我的笔记本电脑没有帮助
  • 在 notebook 代码块中添加断点是可行的(请参见下面的屏幕截图),但我希望能够调试在我的 python 模块文件中编写的代码 enter image description here

版本信息:

  • ipdb-0.12.2
  • python 3.6.9
  • JupyterLab 0.35.5

最佳答案

我认为 magic function %debug 就是您要查找的内容。尝试在 jupyterlab 单元格中插入下面的代码片段并运行它:

def foo(a,b):
    return(a+b)
c = foo(a=1, b=str(1))

这引发了一个TypeError:

enter image description here

现在,如果你在下面插入一个单元格,输入 %debug 并运行它,你会得到这个:

enter image description here

现在你可以运行任何 ipdb command ,比如 h(elp):

enter image description here

希望这个 h(elps)!


编辑:

OP 提供了以下说明:

What I am actually looking for is a proactive way to insert break points, i.e., how to insert breakpoint even if there isn't any error.

在这种情况下,您可以结合使用 from IPython.core.debugger import set_trace 和 ipdb 命令 bt。这是一个例子:

from IPython.core.debugger import set_trace

def foo(a,b):
    return(a+b)
set_trace()
c = foo(a=1, b=1)

这会触发以下内容:

enter image description here

现在,运行命令 bt,我希望你会得到你正在寻找的东西。无论如何,我希望这能回答“没有错误的断点”部分。 我不打算包括运行 bt 的全部输出,因为它很少。但这里是运行 ?bt 的输出以获取有关该特定命令的更多帮助:

enter image description here

关于python - JupyterLab 中的 pdb 未进入交互模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58031628/

相关文章:

python - 如何从 PySpark 中的字符串获取列表

在命令行上运行Python脚本找不到站点包

jupyter-notebook - 如何以编程方式重命名 Jupyter Notebook?

python - 修改单元格的元数据

python - str.contains() 的用法应用于 pandas 数据框

python - Mechanize ._mechanize.FormNotFoundError : no form matching name 'q'

python - PyMySQL 一次查询中的不同更新?

docker - Google Cloud 上的 Jupyter Docker

amazon-web-services - 如何在 AWS EMR notebook 上安装 python 库?

jupyter-notebook - 列出 jupyter 实验室的运行实例