如何跟踪当前在 Jupyter 笔记本中运行的单元?

Fra*_*urt 5 python jupyter-notebook

在Jupyter 笔记本中选择run allrun all aboverun all below后,如何跟踪当前在 Jupyter 笔记本中运行的单元格?即,我希望在笔记本的整个执行过程中向我显示的单元格是正在运行的单元格。

sta*_*son 1

添加以下内容~/.jupyter/custom/custom.js并重新加载您正在运行的笔记本:

/*
 In Command mode Meta-[ toggles Follow Exec Cell mode, Meta-] turns it off.

 To adjust the behavior you can adjust the arguments:
 * behavior: One of "auto", "instant", or "smooth". Defaults to "auto". Defines the transition animation.
 * block:    One of "start", "center", "end", or "nearest". Defaults to "center".
 * inline:   One of "start", "center", "end", or "nearest". Defaults to "nearest".
 https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
*/
function scrollIntoRunningCell(evt, data) {
    $('.running')[0].scrollIntoView({behavior: 'smooth', inline: 'center'});
}

Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Meta-[', {
    help: 'Follow Executing Cell On',
    help_index: 'zz',
    handler: function (event) {
        Jupyter.notebook.events.on('finished_execute.CodeCell', scrollIntoRunningCell);
        //console.log("Follow Executing Cell On")
        return false;
    }
});

Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Meta-]', {
    help: 'Follow Executing Cell Off',
    help_index: 'zz',
    handler: function (event) {
        Jupyter.notebook.events.off('finished_execute.CodeCell', scrollIntoRunningCell);
        //console.log("Follow Executing Cell Off")
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

现在在命令模式下(当焦点所在的单元格周围有一个蓝色框而不是绿色框时,或者按 Esc 键切换模式),点击Meta-[可使当前运行的单元格停留在屏幕中间,点击Meta-]可返回正常行为。

如果这不起作用,请通过取消注释 console.log() 调用来调试此设置,并观察浏览器开发人员工具的控制台以检查 custom.js 是否已加载且没有错误,以及快捷方式是否已注册且处理程序是否已激活。有时您需要重新启动jupyter notebook,但大多数情况下选项卡重新加载都有效。

如果您只想跳转到当前执行单元,Alt-I请在添加以下内容~/.jupyter/custom/custom.js并重新加载正在运行的笔记本后使用:

// Alt-I: Go to Running cell shortcut [Command mode]
Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Alt-I', {
    help : 'Go to Running cell',
    help_index : 'zz',
    handler : function (event) {
        setTimeout(function() {
            // Find running cell and click the first one
            if ($('.running').length > 0) {
                //alert("found running cell");
                $('.running')[0].scrollIntoView();
            }}, 250);
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

警告:为了让它工作 - 这些部分应该全部未折叠 - 否则它不会知道进入折叠部分。

您可以根据自己的喜好调整激活快捷键。

请记住,所有 3 个快捷键仅在命令模式下有效(请参阅上文了解这一点)。

已经过测试,可与 jupyter Notebook 5.6.0 和 python 3.6.6 配合使用。