10

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

Ziofil
  • 1,815
  • 1
  • 20
  • 30
  • 2
    Have you tried doing what's suggested in [this answer](https://stackoverflow.com/a/30942416/9374673)? – Mihai Chelaru Oct 07 '18 at 18:48
  • 1
    I had not seen that, but when I try I get `Javascript Error: IPython is not defined` – Ziofil Oct 07 '18 at 19:11
  • It works just fine for me. I just tested it with a random notebook I had. I'm not sure what the reason for that error is. – Mihai Chelaru Oct 07 '18 at 19:22
  • I tried in jupyter notebook (I was on jupyter lab), I don't get the same error and I can get the filename (which is what I had asked), but I cannot get the full path. – Ziofil Oct 07 '18 at 19:32
  • I'm not sure how you would get the full path or if it's even possible. I did see some others comment the same thing on that other post, but maybe someone else has some idea of how it could be done. – Mihai Chelaru Oct 07 '18 at 19:40
  • @Ziofil, can you please post the solution that worked for you. I have tried various of the javascript solutions suggested at the link Mihai Chelaru posted but none of them work for me. I get JavaScript errors for all of them. I am running Py 3.6, Jupyter 5.0 on Windows 10. – Karl Baker Jan 30 '19 at 01:30

1 Answers1

8

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

AlbHam
  • 104
  • 1
  • 4