【问题标题】:Jupyter notebook custom.js not applied when using "Restarting & Run All"使用“重新启动并全部运行”时未应用 Jupyter notebook custom.js
【发布时间】:2018-10-21 15:42:14
【问题描述】:

为了获取正在运行的 Jupyter notebook 的名称,我首先在 ~/.jupyter/custom/custom.js 中添加了以下行

// Create a nb_name variable with the name of the notebook
IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"');

然后在我的笔记本上运行单元格时:

print(nb_name)

我明白了:

NameError                                 Traceback (most recent call last)
<ipython-input-1-7e37f787d8df> in <module>()
----> 1 print(nb_name)

NameError: name 'nb_name' is not defined

为了解决这个问题,我需要在第一行添加一条警告命令:

alert("hello world from custom.js")

// Create a nb_name variable with the name of the notebook
IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"');

然后当我加载我的笔记本时会出现一个警告窗口,一旦我关闭它,我就会得到预期的笔记本名称。

如何在没有用户任何操作的情况下使其工作(我使用的是笔记本版本 5.0.0,因为我不是服务器的管理员,所以无法更新它)?

编辑:

Waiting for kernel to be ready when executing code via Jupyter kernel (Jupyter Notebook extension) 中的问题部分解决了问题。 Custom.js 文件包含:

Jupyter.notebook.events.one('kernel_ready.Kernel', () => {
     // Create a nb_name variable with the name of the notebook
     IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"');
});

按预期返回笔记本名称。现在的问题是当我“重新启动并运行所有”时,我仍然收到上面提到的错误消息。欢迎任何意见或想法。

【问题讨论】:

    标签: python jupyter-notebook customization


    【解决方案1】:

    custom.js kernel_ready.Kernel 事件仅在页面加载时触发一次,但在 Restart &amp; Run all(或其任何变体)之后不会触发。我对这个问题的解决方案有点老套:

    /**
     * `kernel_ready` logic
     */
    function custom_kernel_ready_handler() {
        IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"');
    }
    
    function handle_kernel_ready() {
        // Create a nb_name variable with the name of the notebook
         console.log('kernel_ready.Kernel: handle_kernel_ready() was triggered!');
         custom_kernel_ready_handler();
    
         Jupyter.notebook.events.one('kernel_ready.Kernel', () => {
             //this recursive behavior is esential for `restart` kernel
             handle_kernel_ready();
        });
    }
    
    Jupyter.notebook.events.one('kernel_ready.Kernel', () => {
         handle_kernel_ready();
    });

    希望有更好的解决方案...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 2017-08-25
      相关资源
      最近更新 更多