116

I am trying to obtain the current NoteBook name when running the IPython notebook. I know I can see it at the top of the notebook. What I am after something like

currentNotebook = IPython.foo.bar.notebookname()

I need to get the name in a variable.

joelostblom
  • 43,590
  • 17
  • 150
  • 159
Tooblippe
  • 3,433
  • 3
  • 17
  • 25
  • What are you trying to do with it? By design, the kernel (the bit that runs code) doesn't know about the frontend (the bit that opens notebooks). – Thomas K Sep 23 '12 at 12:21
  • 7
    Hi, I want to use it with nbconvert to automate the notebook to latex/pdf creation process. My notebooks run remotely. after a class students can download a pdf version of their results. – Tooblippe Sep 26 '12 at 18:40
  • 1
    [P.Toccaceli's answer](https://stackoverflow.com/a/52187331/2166823) works well with recent versions of JupyterLab (1.1.4) (notebook 5.6.0) and does not require javascript. – joelostblom Dec 14 '19 at 15:04
  • 2
    related: https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246 – matth Mar 19 '20 at 09:15
  • 7
    Some did the work and made a pip package: https://pypi.org/project/ipynbname/ install by `pip install ipynbname` – NeoTT Nov 04 '20 at 07:46
  • 2
    Yes `ipynbname` is now working with **jupyter 3** (more details [here](https://stackoverflow.com/questions/62815318/get-current-jupyter-lab-notebook-name-for-jupyter-lab-version-2-1-and-3-0-1-and)) – lhoupert Jan 28 '21 at 08:34
  • `ipynbname` did not work on **jupyter 4** though. –  Oct 18 '21 at 20:34

15 Answers15

50

adding to previous answers,

to get the notebook name run the following in a cell:

%%javascript
IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"')

this gets you the file name in nb_name

then to get the full path you may use the following in a separate cell:

import os
nb_full_path = os.path.join(os.getcwd(), nb_name)
Mahmoud Elagdar
  • 830
  • 6
  • 7
  • 1
    Using `IPython.notebook.notebook_name` this can be done using ```%%javascript IPython.notebook.kernel.execute('notebookName = ' + '"' + IPython.notebook.notebook_name + '"') ``` – jfb Jan 01 '18 at 16:28
  • 15
    For some reason this only work if I run the javascript cell "manually". If I run the full notebook the second cell fails. Any idea why? – Pierre-Antoine Jun 12 '18 at 12:42
  • I guess for some reason, if a variable is modified from javascript then accessed from pure python in the same call, the python version doesn't see the update and also replaces the javascript version. So I guess you may move the javascript cell to the top, run it, then use "Cell>Run All Bellow". – Mahmoud Elagdar Jun 13 '18 at 21:31
  • 6
    Why do we need javascript actually? nothing more native? – matanster Aug 11 '18 at 15:02
  • Let me guess that your python code is sent to a kernel running in the terminal where you launched Jupyter. That kernel doesn't know much about your notebook and the only solution I found so far is using Javascript. There's however a way to run Javascript using iPython, see the following two lines: from IPython.display import Javascript as d_js; d_js("IPython.notebook.kernel.execute('nb_name = \"' + IPython.notebook.notebook_name + '\"')") – Mahmoud Elagdar Aug 12 '18 at 22:42
  • 4
    NameError: name 'nb_name' is not defined – Fernando Wittmann Apr 18 '19 at 21:12
  • Did the JavaScript part run without errors before you ran the Python part? – Mahmoud Elagdar May 01 '19 at 16:15
  • @MahmoudElagdar, `"Cell>Run All Bellow"` doesn't seem an option when remotely running the notebook from another notebook with `%run` – alancalvitti Jul 24 '19 at 14:24
  • 1
    @MahmoudElagdar, the d_js method works in a given notebook when called by a wrapper function, say `notebook_name()` that returns `nb_name`. However, it throws `NameError: name 'nb_name' is not defined ` when `%run` is used to evaluate the notebook containing `notebook_name()`. Any ideas? – alancalvitti Jul 24 '19 at 14:36
  • @alancalvitti perhaps P.Toccaceli's post can help? the problem is you can't set the variable nb_name and use it in the same run because of the way javascript calls are implemented so you have to split it into two runs – Mahmoud Elagdar Aug 30 '19 at 23:50
  • @MahmoudElagdar Can we convert the Javascript part to python? I tried `from IPython import notebook print(IPython.notebook.notebook_name)` But it's throwing error: cannot import name 'notebook'. Please help. Thanks – Arjun A J Sep 27 '19 at 17:55
  • 23
    Fails on Jupyter Lab: `Javascript Error: IPython is not defined` – magicrebirth Nov 26 '19 at 13:35
  • 2
    It's good only for manual execution of a single cell... Javascript calls are async and not guaranteed to complete before python starts running another cell that contains the consumer of this notebook name... resulting in `NameError`. – mirekphd Mar 17 '21 at 11:46
  • 1
    @mirekphd The async idea is interesting, IDK I tried adding a sleep and still didn't work. Maybe try P.Toccaceli's solution – Mahmoud Elagdar Mar 19 '21 at 23:32
42

I have the following which works with IPython 2.0. I observed that the name of the notebook is stored as the value of the attribute 'data-notebook-name' in the <body> tag of the page. Thus the idea is first to ask Javascript to retrieve the attribute --javascripts can be invoked from a codecell thanks to the %%javascript magic. Then it is possible to access to the Javascript variable through a call to the Python Kernel, with a command which sets a Python variable. Since this last variable is known from the kernel, it can be accessed in other cells as well.

%%javascript
var kernel = IPython.notebook.kernel;
var body = document.body,  
    attribs = body.attributes;
var command = "theNotebook = " + "'"+attribs['data-notebook-name'].value+"'";
kernel.execute(command);

From a Python code cell

print(theNotebook)

Out[ ]: HowToGetTheNameOfTheNoteBook.ipynb

A defect in this solution is that when one changes the title (name) of a notebook, then this name seems to not be updated immediately (there is probably some kind of cache) and it is necessary to reload the notebook to get access to the new name.

[Edit] On reflection, a more efficient solution is to look for the input field for notebook's name instead of the <body> tag. Looking into the source, it appears that this field has id "notebook_name". It is then possible to catch this value by a document.getElementById() and then follow the same approach as above. The code becomes, still using the javascript magic

%%javascript
var kernel = IPython.notebook.kernel;
var thename = window.document.getElementById("notebook_name").innerHTML;
var command = "theNotebook = " + "'"+thename+"'";
kernel.execute(command);

Then, from a ipython cell,

In [11]: print(theNotebook)
Out [11]: HowToGetTheNameOfTheNoteBookSolBis

Contrary to the first solution, modifications of notebook's name are updated immediately and there is no need to refresh the notebook.

jfb
  • 679
  • 6
  • 9
  • Maybe I missed something, but how do you invoke the javascript code from python? – Artjom B. May 12 '14 at 22:18
  • 7
    It is also possible to call the javascript from within python using the display method applied to a javascript object like `def getname(): display(Javascript('IPython.notebook.kernel.execute("theNotebook = " + "\'"+IPython.notebook.notebook_name+"\'");'))` – Jakob Jun 04 '14 at 21:14
  • How do I modify this to get the notebook's path? – Pedro M Duarte Mar 23 '15 at 03:59
  • @PedroMDuarte: You can use IPython.notebook.notebook_path in javascript for 'thename' in the above script to get that value. – Tristan Reid Apr 07 '15 at 22:12
  • @PedroMDuarte: Note that the path is relative to the root of the notebook server. – Tristan Reid Apr 07 '15 at 22:16
  • @Jakob: it works fine if done in a cell, but not in a function as you have it. I asked a [question about this here](http://stackoverflow.com/q/30902898/758174). – Pierre D Jun 17 '15 at 22:50
  • @PierreD Well, you cannot immediately return the value but it gets stored as _theNotebook_. Nevertheless, I also would prefer a solution to directly get such variables. – Jakob Jun 18 '15 at 05:06
  • The second solution, which looks for the notebook-name `` element has another advantage: If you rename a notebook, this method immediately reflects this, while the body attribute is only updated when you close and re-open the notebook. – Sunday Sep 05 '18 at 09:38
  • 4
    To get the notebook path without JS trickery: `globals()['_dh'][0]` – germ Jul 21 '19 at 21:49
  • I tried but got "ReferenceError: Can't find variable: IPython" on the browser console log. I also tried to "Import IPython" in a code cell before executing this, same issue. Btw: I am trying this on google colab, perhaps this doesn't work there? – kawingkelvin Mar 03 '20 at 05:40
  • @BND, just tried it on IPython 7.12.0 and Python 3.7: It works. What versions are you using? – germ Nov 22 '20 at 06:16
31

As already mentioned you probably aren't really supposed to be able to do this, but I did find a way. It's a flaming hack though so don't rely on this at all:

import json
import os
import urllib2
import IPython
from IPython.lib import kernel
connection_file_path = kernel.get_connection_file()
connection_file = os.path.basename(connection_file_path)
kernel_id = connection_file.split('-', 1)[1].split('.')[0]

# Updated answer with semi-solutions for both IPython 2.x and IPython < 2.x
if IPython.version_info[0] < 2:
    ## Not sure if it's even possible to get the port for the
    ## notebook app; so just using the default...
    notebooks = json.load(urllib2.urlopen('http://127.0.0.1:8888/notebooks'))
    for nb in notebooks:
        if nb['kernel_id'] == kernel_id:
            print nb['name']
            break
else:
    sessions = json.load(urllib2.urlopen('http://127.0.0.1:8888/api/sessions'))
    for sess in sessions:
        if sess['kernel']['id'] == kernel_id:
            print sess['notebook']['name']
            break

I updated my answer to include a solution that "works" in IPython 2.0 at least with a simple test. It probably isn't guaranteed to give the correct answer if there are multiple notebooks connected to the same kernel, etc.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63
  • connection_file_path = kernel.get_connection_file() doesn't work anymore, filename is required arg. – Purrell Oct 29 '13 at 18:57
  • This worked fine for me on IPython.__version__ of '0.13.2' and I didnot have to specify a filename for the kernel.get_connection_file() – Paul Nov 18 '13 at 14:47
  • 2
    Some updates: Instead of `from IPython.lib import kernel` now it's just `from IPython import kernel`. Also instead of using the key 'name' in the dictionaries, use the key 'path' – Tristan Reid Nov 24 '15 at 20:02
  • 1
    As advertised by the answerer himself, this answer doesn't work for latest IPython. I've created a version that seems to work with IPython 4.2.0 in Python 3.5: https://gist.github.com/mbdevpl/f97205b73610dd30254652e7817f99cb – mbdevpl Jul 09 '16 at 11:59
  • 1
    As of version 4.3.0, you need to provide an auth token. This can be retrieved using `notebook.notebookapp.list_running_servers()`. – yingted Aug 20 '17 at 05:11
  • 1
    If you have multiple servers running, you can check what port the kernel's parent process is listening on, which should tell you which server to connect to (or you can just connect to every local Jupyter server and check which is running your kernel). – yingted Aug 20 '17 at 05:14
  • if you have multiple servers running, you can list all of them using `!jupyter notebook list` This will give all running notebooks and then use the one with the correct pwd, or just check them all – ntg Sep 24 '20 at 20:24
  • This may be outdated, another answer in this thread below shows that not only it is fine but fairly easy to get the name of the current notebook from within itself. – alejandro Oct 27 '20 at 13:06
31

It seems I cannot comment, so I have to post this as an answer.

The accepted solution by @iguananaut and the update by @mbdevpl appear not to be working with recent versions of the Notebook. I fixed it as shown below. I checked it on Python v3.6.1 + Notebook v5.0.0 and on Python v3.6.5 and Notebook v5.5.0.

import jupyterlab
if jupyterlab.__version__.split(".")[0] == "3":
    from jupyter_server import serverapp as app
    key_srv_directory = 'root_dir'
else : 
    from notebook import notebookapp as app
    key_srv_directory = 'notebook_dir'
import urllib
import json
import os
import ipykernel

def notebook_path(key_srv_directory, ):
    """Returns the absolute path of the Notebook or None if it cannot be determined
    NOTE: works only when the security is token-based or there is also no password
    """
    connection_file = os.path.basename(ipykernel.get_connection_file())
    kernel_id = connection_file.split('-', 1)[1].split('.')[0]

    for srv in app.list_running_servers():
        try:
            if srv['token']=='' and not srv['password']:  # No token and no password, ahem...
                req = urllib.request.urlopen(srv['url']+'api/sessions')
            else:
                req = urllib.request.urlopen(srv['url']+'api/sessions?token='+srv['token'])
            sessions = json.load(req)
            for sess in sessions:
                if sess['kernel']['id'] == kernel_id:
                    return os.path.join(srv[key_srv_directory],sess['notebook']['path'])
        except:
            pass  # There may be stale entries in the runtime directory 
    return None

As stated in the docstring, this works only when either there is no authentication or the authentication is token-based.

Note that, as also reported by others, the Javascript-based method does not seem to work when executing a "Run all cells" (but works when executing cells "manually"), which was a deal-breaker for me.

InLaw
  • 2,537
  • 2
  • 21
  • 33
P.Toccaceli
  • 771
  • 8
  • 9
  • 1
    Is there any library for this? – matanster Nov 02 '18 at 11:11
  • 1
    The failure of Javascript methods was a deal-breaker for me too. Thanks for posting this alternative! – gumption Nov 06 '19 at 23:17
  • I have to replace srv['notebook_dir'] with from jupyter_core.paths import jupyter_config_dir; from traitlets.config import Config; c = Config(); file_path = os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.py'); exec(open(file_path).read()); root_dir = c['FileContentsManager']['root_dir'] – Dave Babbitt Dec 22 '19 at 13:06
  • @P.Toccaceli making lots of assumptions for when line count is relevant, maybe it can be reduced to this ```from jupyter_server import serverapp as app; import ipykernel, requests, os; kernel_id = os.path.basename(ipykernel.get_connection_file()).split('-', 1)[1].split('.')[0]; srv = next(app.list_running_servers()); nb_path = srv["root_dir"]+"/"+next(s for s in requests.get(srv['url']+'api/sessions?token='+srv['token']).json() if s["kernel"]["id"]==kernel_id)['notebook']['path']``` – Mahmoud Elagdar Mar 19 '21 at 23:29
31

The ipyparams package can do this pretty easily.

import ipyparams
currentNotebook = ipyparams.notebook_name
Bill
  • 518
  • 5
  • 10
  • 2
    Hi @bill, I tried this solution on recent jupyter notebook version but I didn't manage to make it work. I create a post [[here](https://stackoverflow.com/questions/62815318/get-current-jupyter-lab-notebook-name-for-jupyter-lab-version-2-1-and-notebook)] – lhoupert Jan 20 '21 at 13:43
  • 9
    I found the solution with the package [ipynbname](https://pypi.org/project/ipynbname/) – lhoupert Jan 28 '21 at 08:37
  • as usual on SO - the marked answer is prob most unhelpful and the best answer is buried on the bottom – Boppity Bop Sep 17 '22 at 15:32
  • [ipynbname](https://anaconda.org/conda-forge/ipynbname) is also now on conda. `conda install -c conda-forge ipynbname` – intotecho Feb 17 '23 at 02:56
28

On Jupyter 3.0 the following works. Here I'm showing the entire path on the Jupyter server, not just the notebook name:

To store the NOTEBOOK_FULL_PATH on the current notebook front end:

%%javascript
var nb = IPython.notebook;
var kernel = IPython.notebook.kernel;
var command = "NOTEBOOK_FULL_PATH = '" + nb.base_url + nb.notebook_path + "'";
kernel.execute(command);

To then display it:

print("NOTEBOOK_FULL_PATH:\n", NOTEBOOK_FULL_PATH)

Running the first Javascript cell produces no output. Running the second Python cell produces something like:

NOTEBOOK_FULL_PATH:
 /user/zeph/GetNotebookName.ipynb
8

Yet another hacky solution since my notebook server can change. Basically you print a random string, save it and then search for a file containing that string in the working directory. The while is needed because save_checkpoint is asynchronous.

from time import sleep
from IPython.display import display, Javascript
import subprocess
import os
import uuid

def get_notebook_path_and_save():
    magic = str(uuid.uuid1()).replace('-', '')
    print(magic)
    # saves it (ctrl+S)
    display(Javascript('IPython.notebook.save_checkpoint();'))
    nb_name = None
    while nb_name is None:
        try:
            sleep(0.1)
            nb_name = subprocess.check_output(f'grep -l {magic} *.ipynb', shell=True).decode().strip()
        except:
            pass
    return os.path.join(os.getcwd(), nb_name)
MartínV
  • 185
  • 1
  • 5
  • This is great. Other Javascript based solutions haven't been working well in my environment (sagemaker studio). This one does though! – Warlax56 Sep 03 '21 at 17:39
  • Why does it require the 'while' loop, why does 'grep' need to be re-run so many times? – Alec K Jan 31 '23 at 18:30
6

There is no real way yet to do this in Jupyterlab. But there is an official way that's now under active discussion/development as of August 2021:

https://github.com/jupyter/jupyter_client/pull/656

In the meantime, hitting the api/sessions REST endpoint of jupyter_server seems like the best bet. Here's a cleaned-up version of that approach:

from jupyter_server import serverapp
from jupyter_server.utils import url_path_join
from pathlib import Path
import re
import requests

kernelIdRegex = re.compile(r"(?<=kernel-)[\w\d\-]+(?=\.json)")

def getNotebookPath():
    kernelId = kernelIdRegex.search(get_ipython().config["IPKernelApp"]["connection_file"])[0]
    
    for jupServ in serverapp.list_running_servers():
        for session in requests.get(url_path_join(jupServ["url"], "api/sessions"), params={"token": jupServ["token"]}).json():
            if kernelId == session["kernel"]["id"]:
                return Path(jupServ["root_dir"]) / session["notebook"]['path']

Tested working with

python==3.9
jupyter_server==1.8.0
jupyterlab==4.0.0a7
tel
  • 13,005
  • 2
  • 44
  • 62
  • 1
    I always thought of so many applications of knowing the notebook filename (e.g. based on the filename one could import different sets of modules for a given notebook). Truly this functionality is much needed, ideally it should be perhaps built into the jupyter's core package itself. –  Oct 18 '21 at 20:39
  • @Ramirez Literally no one on Stackoverflow cares about your two cents. However, if you post your view/use cases to the ["pass notebook name to kernel" feature discussion thread](https://github.com/jupyter/jupyter_client/pull/656), the actual Jupyter devs will read them and likely respond – tel Oct 26 '21 at 00:21
  • Thank you! Worked for me, with jupyterlab==3.3.4 and Python 3.7 – Julian - BrainAnnex.org Jun 05 '22 at 04:21
4

just use ipynbname , which is practical

#! pip install ipynbname

import ipynbname
nb_fname = ipynbname.name()
nb_path = ipynbname.path()
print(f"{nb_fname=}")
print(f"{nb_path=}")

I found this in https://stackoverflow.com/a/65907473/15497427

138 Aspen
  • 141
  • 5
3

Modifying @jfb method, gives the function below which worked fine on ipykernel-5.3.4.

def getNotebookName():
    display(Javascript('IPython.notebook.kernel.execute("NotebookName = " + "\'"+window.document.getElementById("notebook_name").innerHTML+"\'");'))
    try:
        _ = type(NotebookName)
        return NotebookName
    except:
        return None

Note that the display javascript will take some time to reach the browser, and it will take some time to execute the JS and get back to the kernel. I know it may sound stupid, but it's better to run the function in two cells, like this:

nb_name = getNotebookName()

and in the following cell:

for i in range(10):
    nb_name = getNotebookName()
    if nb_name is not None:
        break

However, if you don't need to define a function, the wise method is to run display(Javascript(..)) in one cell, and check the notebook name in another cell. In this way, the browser has enough time to execute the code and return the notebook name.

If you don't mind to use a library, the most robust way is:

import ipynbname
nb_name = ipynbname.name()
Mehdi
  • 999
  • 13
  • 11
  • 2
    The option with ipynbname is the ONLY ONE straight forward. All the other I have to deal with installation of IPyton, Javablahblah, and so on. Thanks – alEx Dec 01 '21 at 07:50
  • ipynbname takes 16 seconds to execute in my minimal notebook. – BSalita Jun 12 '22 at 17:47
  • 1
    @BSalita - latest version of ipynbname is faster. You may have many old and stale nbserver files, assuming you are using JupyterLab. – msm1089 Jul 25 '23 at 20:52
3

If you are using Visual Studio Code:

import IPython ; IPython.extract_module_locals()[1]['__vsc_ipynb_file__']
AntoninX
  • 31
  • 1
2

To realize why you can't get notebook name using these JS-based solutions, run this code and notice the delay it takes for the message box to appear after python has finished execution of the cell / entire notebook:

%%javascript

function sayHello() {
    alert('Hello world!');
}

setTimeout(sayHello, 1000);
  • More info

Javascript calls are async and hence not guaranteed to complete before python starts running another cell containing the code expecting this notebook name variable to be already created... resulting in NameError when trying to access non-existing variables that should contain notebook name.

I suspect some upvotes on this page became locked before voters could discover that all %%javascript-based solutions ultimately don't work... when the producer and consumer notebook cells are executed together (or in a quick succession).

mirekphd
  • 4,799
  • 3
  • 38
  • 59
1

Assuming you have the Jupyter Notebook server's host, port, and authentication token, this should work for you. It's based off of this answer.

import os
import json
import posixpath
import subprocess
import urllib.request
import psutil

def get_notebook_path(host, port, token):
    process_id = os.getpid();
    notebooks = get_running_notebooks(host, port, token)
    for notebook in notebooks:
        if process_id in notebook['process_ids']:
            return notebook['path']

def get_running_notebooks(host, port, token):
    sessions_url = posixpath.join('http://%s:%d' % (host, port), 'api', 'sessions')
    sessions_url += f'?token={token}'
    response = urllib.request.urlopen(sessions_url).read()
    res = json.loads(response)
    notebooks = [{'kernel_id': notebook['kernel']['id'],
                  'path': notebook['notebook']['path'],
                  'process_ids': get_process_ids(notebook['kernel']['id'])} for notebook in res]
    return notebooks

def get_process_ids(name):
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    return [int(pid) for pid in response.split()]

Example usage:

get_notebook_path('127.0.0.1', 17004, '344eb91bee5742a8501cc8ee84043d0af07d42e7135bed90')
Caleb Koch
  • 656
  • 1
  • 9
  • 15
1

All Json based solutions fail if we execute more than one cell at a time because the result will not be ready until after the end of the execution (its not a matter of using sleep or waiting any time, check it yourself but remember to restart kernel and run all every test)

Based on previous solutions, this avoids using the %% magic in case you need to put it in the middle of some other code:

from IPython.display import display, Javascript

# can have comments here :)
js_cmd = 'IPython.notebook.kernel.execute(\'nb_name = "\' + IPython.notebook.notebook_name + \'"\')'
display(Javascript(js_cmd))

For python 3, the following based on the answer by @Iguananaut and updated for latest python and possibly multiple servers will work:

import os
import json
try:
    from urllib2 import urlopen
except:
    from urllib.request import urlopen
import ipykernel

connection_file_path = ipykernel.get_connection_file()
connection_file = os.path.basename(connection_file_path)
kernel_id = connection_file.split('-', 1)[1].split('.')[0]    
    
running_servers = !jupyter notebook list
running_servers = [s.split('::')[0].strip() for s in running_servers[1:]]
nb_name = '???'
for serv in running_servers:
    uri_parts = serv.split('?')
    uri_parts[0] += 'api/sessions'
    sessions = json.load(urlopen('?'.join(uri_parts)))
    for sess in sessions:
        if sess['kernel']['id'] == kernel_id:
            nb_name = os.path.basename(sess['notebook']['path'])
            break
    if nb_name != '???':
        break
print (f'[{nb_name}]')
    
ntg
  • 12,950
  • 7
  • 74
  • 95
1

Nowadays this was implemented as a feature in IPython, there is a built-in "vsc_ipynb_file" variable.

This is the fix - https://github.com/microsoft/vscode-jupyter/pull/8531

kenissur
  • 171
  • 1
  • 2
  • 7