问题
In order to get the name of a running Jupyter notebook, I first added the following line in ~/.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 + '"');
Then on my notebook when I run a cell with:
print(nb_name)
I get:
NameError Traceback (most recent call last)
<ipython-input-1-7e37f787d8df> in <module>()
----> 1 print(nb_name)
NameError: name 'nb_name' is not defined
To solve this issue I need to add a first line with an alert command:
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 + '"');
Then an alert window shows up when I load my notebook, and once I closed it, I get the notebook name as expected.
How could I make it work without any action from the user (I am using notebook version 5.0.0 and as I am not the admin of the server cannot update it)?
EDIT:
Question in Waiting for kernel to be ready when executing code via Jupyter kernel (Jupyter Notebook extension) solved partially the problem. Custom.js file containing:
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 + '"');
});
Return the notebook name as expected. Now the problem is I still get the error message mentioned above when I "Restart & Run All". Any comment or idea would be welcome.
回答1:
custom.js kernel_ready.Kernel
event is triggered only once when the page is loaded, but it is not triggered after Restart & Run all
(or any variants of it). My solution to this problem is a bit hackie:
/**
* `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();
});
Hoping for better solutions ...
来源:https://stackoverflow.com/questions/52917023/jupyter-notebook-custom-js-not-applied-when-using-restarting-run-all