IPython
Jupyter Notebook
Python Programming
Notebook Name Retrieval
Code Tutorial

How do I get the current IPython / Jupyter Notebook name

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Getting the current Jupyter notebook's filename is not straightforward because the notebook runs in a client-server architecture where the kernel does not directly know which notebook file it belongs to. The most reliable methods are: using ipynbname (a dedicated library), querying the Jupyter server API, or using JavaScript to read the notebook name from the browser. For JupyterLab, the jpserver_extensions API and environment variables provide additional options.

Method 1: ipynbname Library (Simplest)

python
1# pip install ipynbname
2import ipynbname
3
4# Get the notebook filename
5nb_fname = ipynbname.name()
6print(nb_fname)  # "my_analysis"
7
8# Get the full path
9nb_path = ipynbname.path()
10print(nb_path)  # PosixPath('/home/user/notebooks/my_analysis.ipynb')

ipynbname queries the Jupyter server API to find which notebook file is connected to the current kernel. It works in both Jupyter Notebook and JupyterLab.

Method 2: Query the Jupyter Server API

python
1import json
2import os
3import urllib.request
4import re
5
6def get_notebook_name():
7    """Get the current notebook name by querying the Jupyter server."""
8    # Get connection info from IPython
9    from IPython import get_ipython
10    kernel = get_ipython().kernel
11    connection_file = kernel.config['IPKernelApp']['connection_file']
12    kernel_id = os.path.basename(connection_file).replace('kernel-', '').replace('.json', '')
13
14    # Get the Jupyter server URL and token
15    from notebook.notebookapp import list_running_servers
16    for server in list_running_servers():
17        url = f"{server['url']}api/sessions?token={server['token']}"
18        try:
19            response = urllib.request.urlopen(url)
20            sessions = json.loads(response.read().decode())
21            for sess in sessions:
22                if sess['kernel']['id'] == kernel_id:
23                    return sess['notebook']['name']
24        except Exception:
25            continue
26    return None
27
28name = get_notebook_name()
29print(name)  # "my_analysis.ipynb"

Method 3: JavaScript Bridge (Classic Notebook)

python
1from IPython.display import Javascript, display
2
3# This only works in classic Jupyter Notebook (not JupyterLab)
4display(Javascript('IPython.notebook.kernel.execute("nb_name = \'" + IPython.notebook.notebook_name + "\'")'))
5
6# After running the cell above, nb_name is set in the Python kernel
7print(nb_name)  # "my_analysis.ipynb"

This method uses the browser's JavaScript context to read the notebook name and inject it into the Python kernel. It does not work in JupyterLab or headless execution.

Method 4: Using vsc_ipynb_file (VS Code)

python
1import os
2
3# VS Code sets this variable when running notebooks
4if hasattr(__builtins__, '__vsc_ipynb_file__'):
5    nb_path = __vsc_ipynb_file__
6    nb_name = os.path.basename(nb_path)
7    print(nb_name)
8
9# Alternative: check globals
10nb_path = globals().get('__vsc_ipynb_file__', None)
11if nb_path:
12    print(os.path.basename(nb_path))

Method 5: Environment Variable Approach

python
1import os
2
3# Some Jupyter configurations set JUPYTER_NOTEBOOK_PATH
4nb_path = os.environ.get('JPY_SESSION_NAME', '')
5if nb_path:
6    print(os.path.basename(nb_path))
7
8# Papermill sets PAPERMILL_NOTEBOOK_NAME
9pm_name = os.environ.get('PAPERMILL_NOTEBOOK_NAME', '')
10if pm_name:
11    print(pm_name)

Practical Use Cases

python
1import ipynbname
2from datetime import datetime
3
4# Use notebook name for logging
5nb_name = ipynbname.name()
6log_file = f"logs/{nb_name}_{datetime.now():%Y%m%d_%H%M}.log"
7print(f"Logging to: {log_file}")
8
9# Use notebook name for saving outputs
10import pandas as pd
11df = pd.DataFrame({"a": [1, 2, 3]})
12output_file = f"results/{nb_name}_output.csv"
13df.to_csv(output_file, index=False)
14
15# Use notebook name in experiment tracking
16import mlflow
17mlflow.set_experiment(nb_name)
18with mlflow.start_run(run_name=f"{nb_name}_run"):
19    mlflow.log_param("notebook", nb_name)

Fallback Pattern

python
1def get_notebook_name():
2    """Try multiple methods to get the notebook name."""
3    # Method 1: ipynbname
4    try:
5        import ipynbname
6        return str(ipynbname.name())
7    except Exception:
8        pass
9
10    # Method 2: VS Code variable
11    try:
12        import os
13        path = globals().get('__vsc_ipynb_file__')
14        if path:
15            return os.path.splitext(os.path.basename(path))[0]
16    except Exception:
17        pass
18
19    # Method 3: Jupyter server API
20    try:
21        return query_jupyter_api()  # from Method 2 above
22    except Exception:
23        pass
24
25    # Method 4: Environment variable
26    import os
27    name = os.environ.get('JPY_SESSION_NAME', '')
28    if name:
29        return os.path.splitext(os.path.basename(name))[0]
30
31    return "unknown_notebook"
32
33print(get_notebook_name())

Common Pitfalls

  • Using JavaScript injection in JupyterLab: The IPython.notebook.notebook_name JavaScript variable exists only in the classic Jupyter Notebook interface. JupyterLab has a different DOM structure, and the IPython.notebook object does not exist. Use ipynbname or the server API instead, which work in both environments.
  • list_running_servers() import path changed: In newer versions of Jupyter, list_running_servers moved from notebook.notebookapp to jupyter_server.serverapp. If you get an ImportError, try from jupyter_server.serverapp import list_running_servers as a fallback.
  • Notebook name not available during non-interactive execution: When a notebook is executed by papermill, nbconvert, or a CI pipeline, there is no Jupyter server to query. ipynbname and the server API both fail. Use environment variables or pass the notebook name as a parameter in these cases.
  • Kernel restart clearing the JavaScript-injected variable: If you use the JavaScript bridge method to set nb_name in the Python kernel, restarting the kernel clears all Python variables including nb_name. You must re-run the JavaScript cell after every kernel restart. Library-based methods do not have this issue.
  • Security token required for server API queries: The Jupyter server API requires an authentication token. list_running_servers() provides the token from the local server config, but in multi-user environments (JupyterHub), the token may differ or require explicit configuration. ipynbname handles this internally.

Summary

  • Use ipynbname (pip install ipynbname) for the simplest, most portable solution
  • Query the Jupyter server API for environments where you cannot install packages
  • Use __vsc_ipynb_file__ when running notebooks in VS Code
  • Implement a fallback chain that tries multiple methods for maximum compatibility
  • For non-interactive execution (papermill, CI), pass the notebook name as a parameter or environment variable

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.