Jupyter Notebook Enhancements, Tips And Tricks

Getting the notebook name automatically

# cell 1
%%javascript
IPython.notebook.kernel.execute('nb_name = ' + '"' + IPython.notebook.notebook_name + '"')
# cell 2
nb_name

Same without js magic:

# cell 1
from IPython.display import display, Javascript
Javascript("IPython.notebook.kernel.execute('nb_name = ' + '\"' + IPython.notebook.notebook_name + '\"')")
# cell 2
nb_name

In either case, JS is async - so it may not run right away and therefore it’s not guaranteed nb_name will be set right away.

I was looking for this feature, since I wanted to replace hardcoded cells in each dev_nbs such as:

!./notebook2script.py 02_fully_connected.ipynb

with something similar that will extract the nb name automatically.

So I wrote a little helper function:

from IPython.display import display, Javascript
def nb_auto_export():
    display(Javascript("if (IPython.notebook.kernel) {IPython.notebook.kernel.execute('!./notebook2script.py ' + IPython.notebook.notebook_name )}"))

(it looks like JS is the only way to get the nb name in jupyter :frowning:)

notes:

  • it assumes the nb name has no spaces in it, add quotes if it does
  • had to bracket the code with if (IPython.notebook.kernel) {} since the browser will attempt to run this js code automatically on jupyter nb load and fail, since IPython.notebook.kernel hasn’t been defined yet. It only happens if there is ! in the js code - odd.

and now there is no need to hardcode the nb name, just have the last cell say:

nb_auto_export()

that is if you imported nb_auto_export from somewhere you saved it.

Or alternatively without needing to import anything, you could just have the last cell of each notebook:

%%javascript 
if (IPython.notebook.kernel) {
    IPython.notebook.kernel.execute('!./notebook2script.py ' + IPython.notebook.notebook_name)
}

Also note that it’s async, so it usually takes a sec or so to start running once the nb finished running.

Or the messier approach w/o js magic:

from IPython.display import display, Javascript
display(Javascript("if (IPython.notebook.kernel) {IPython.notebook.kernel.execute('!./notebook2script.py ' + IPython.notebook.notebook_name)}"))

You might be able to drop display from it, but it seems not to work w/o it for me.

Finally, you shouldn’t rely on auto-save, since you’re likely to miss recent changes, so why not tell this code to save the notebook first, resulting in this code:

from IPython.display import display, Javascript
def nb_auto_export():
    display(Javascript("if (IPython.notebook) { IPython.notebook.save_notebook() }; if (IPython.notebook.kernel) { IPython.notebook.kernel.execute('!./notebook2script.py  ' + IPython.notebook.notebook_name )}"))

Ideas for this solution came from SO: 1, 2

2 Likes