Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a jupyter notebook find its own filename?

Is it possible for a jupyter notebook to get the name of its own file, similarly to what we would do from a python script?

os.path.basename(__file__) doesn't seem to work, at least for me on jupyterlab

sys.argv[0] returns my_home/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py

like image 892
Ziofil Avatar asked Oct 07 '18 18:10

Ziofil


People also ask

What is the file name for Jupyter notebook?

Jupyter notebooks have the file extension “. ipynb”. Clicking on files ending with “. ipynb” opens the notebook.

How do I trace a Jupyter notebook?

The easiest way to debug a Jupyter notebook is to use the %debug magic command. Whenever you encounter an error or exception, just open a new notebook cell, type %debug and run the cell. This will open a command line where you can test your code and inspect all variables right up to the line that threw the error.


1 Answers

The only way I've found is through JavaScritp as in this answer.

The compact form is a cell like this:

%%javascript
IPython.notebook.kernel.execute(`notebookName = '${window.document.getElementById("notebook_name").innerHTML}'`);

after that you'll have the variable notebookName with the name that appears at the top of the page.

A better solution may be using IPython.notebook.notebook_name:

%%javascript
IPython.notebook.kernel.execute(`notebookName = '${IPython.notebook.notebook_name}'`);

it gives you the name with the extension .ipynb

like image 126
AlbHam Avatar answered Sep 28 '22 07:09

AlbHam