Jupyter 中的调试和运行模式

Wal*_*eed 2 python ipython pdb ipdb jupyter-notebook

就像在 matlab 中一样,Jupyter 中是否有可能在调试模式下运行函数,其中执行在断点处暂停,而在运行模式下函数会忽略断点?在一个简单的例子中,比如

from IPython.core.debugger import set_trace

def debug(y):
    x = 10
    x = x + y 
    set_trace()
    for i in range(10):
        x = x+i
    return x

debug(10)
Run Code Online (Sandbox Code Playgroud)

我们是否有可能调用该函数以使 set_trace 被忽略并且函数正常运行?

我想要这个的原因是,在我的函数中,我放置了很多设置跟踪,当我只想在没有跟踪的情况下运行时,我需要注释所有设置跟踪。有更容易的方法吗?

Mat*_*ith 5

我不知道有什么方法可以直接使用 Jupyter 执行此操作,但是您可以做的就是set_trace()像这样进行猴子修补(我建议将其放在自己的单元格中,以便您可以在需要时重新运行它重新打开调试):

from IPython.core.debugger import set_trace
debug_mode = False #switch this to True if you want debugging back on
if not debug_mode:
  def pass_func():
    pass
  set_trace = pass_func
Run Code Online (Sandbox Code Playgroud)

它的作用是将名称重新绑定set_trace为一个不执行任何操作的函数,因此每次set_trace()调用时,它都会只是pass.

如果您希望重新打开调试,只需将debug_mode标志切换为True并重新运行单元即可。set_trace然后,这将重新绑定要从set_trace导入的名称IPython.core.debugger