Skip to main content
 首页 » 编程设计

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

2024年11月01日12www_RR

我的目标是在 JupyterLab 中使用 pdb 或 ipdb 运行一些 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 也是如此。


我尝试过的事情:

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

版本信息:

  • 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:

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

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

希望这个 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) 

这会触发以下内容:

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