├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── ipynbname └── __init__.py ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.ipynb* 2 | **/ipynb_checkpoints 3 | **/build 4 | **/dist 5 | **/__pycache__ 6 | *.egg-info 7 | **/test 8 | **/.vscode 9 | *.txt 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Mark McPherson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ipynbname 2 | 3 | When run in a Jupyter notebook, simply returns the notebook filename or the full path to the notebook. 4 | I created this to help with automating posting blog posts written in Jupyter notebooks directly to 5 | GitHub Pages. 6 | 7 | You would think there was already some built-in way to access the current notebook name, but it took many hours 8 | of searching for a way to do it. As it seems many others did, I tried using Javascript, but the async nature of 9 | JS meant that it was unreliable. Finally I stumbled on this [post](https://forums.fast.ai/t/jupyter-notebook-enhancements-tips-and-tricks/17064/39). 10 | I have refactored the code there so a user can get either the name or path, but credit for most of the code 11 | goes to the author of this post, thanks! 12 | 13 | ## Examples 14 | 15 | Get the notebook name: 16 | 17 | ```python 18 | import ipynbname 19 | nb_fname = ipynbname.name() 20 | ``` 21 | 22 | Get the full path to the notebook: 23 | 24 | ```python 25 | import ipynbname 26 | nb_path = ipynbname.path() 27 | ``` 28 | ## Limitations 29 | 30 | Note that this only reliably works when running a notebook in a browser. So it does not currently work for things like nbconvert or papermill. 31 | 32 | For VS Code there is a [workaround](https://github.com/msm1089/ipynbname/issues/17#issuecomment-1293269863). 33 | -------------------------------------------------------------------------------- /ipynbname/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import os 4 | import urllib.error 5 | import urllib.request 6 | from itertools import chain 7 | from pathlib import Path, PurePath 8 | from typing import Generator, Tuple, Union 9 | 10 | import ipykernel 11 | from jupyter_core.paths import jupyter_runtime_dir 12 | from traitlets.config import MultipleInstanceError 13 | 14 | 15 | FILE_ERROR = "Can't identify the notebook {}." 16 | CONN_ERROR = "Unable to access server;\n" \ 17 | + "ipynbname requires either no security or token based security." 18 | 19 | 20 | def _list_maybe_running_servers(runtime_dir=None) -> Generator[dict, None, None]: 21 | """ Iterate over the server info files of running notebook servers. 22 | """ 23 | if runtime_dir is None: 24 | runtime_dir = jupyter_runtime_dir() 25 | runtime_dir = Path(runtime_dir) 26 | 27 | if runtime_dir.is_dir(): 28 | # Get notebook configuration files, sorted to check the more recently modified ones first 29 | for file_name in sorted( 30 | chain( 31 | runtime_dir.glob('nbserver-*.json'), # jupyter notebook (or lab 2) 32 | runtime_dir.glob('jpserver-*.json'), # jupyterlab 3 33 | ), 34 | key=os.path.getmtime, 35 | reverse=True, 36 | ): 37 | try: 38 | yield json.loads(file_name.read_bytes()) 39 | except json.JSONDecodeError as err: 40 | # Sometimes we encounter empty JSON files. Ignore them. 41 | pass 42 | 43 | 44 | def _get_kernel_id() -> str: 45 | """ Returns the kernel ID of the ipykernel. 46 | """ 47 | connection_file = Path(ipykernel.get_connection_file()).stem 48 | kernel_id = connection_file.split('-', 1)[1] 49 | return kernel_id 50 | 51 | 52 | def _get_sessions(srv): 53 | """ Given a server, returns sessions, or HTTPError if access is denied. 54 | NOTE: Works only when either there is no security or there is token 55 | based security. An HTTPError is raised if unable to connect to a 56 | server. 57 | """ 58 | try: 59 | qry_str = "" 60 | token = srv['token'] 61 | if not token and "JUPYTERHUB_API_TOKEN" in os.environ: 62 | token = os.environ["JUPYTERHUB_API_TOKEN"] 63 | qry_str = f"?token={token}" if token else "" 64 | url = f"{srv['url']}api/sessions{qry_str}" 65 | # Use a timeout in case this is a stale entry. 66 | with urllib.request.urlopen(url, timeout=0.5) as req: 67 | return json.load(req) 68 | except Exception: 69 | raise urllib.error.HTTPError(CONN_ERROR) 70 | 71 | 72 | def _find_nb_path() -> Union[Tuple[dict, PurePath], Tuple[None, None]]: 73 | try: 74 | kernel_id = _get_kernel_id() 75 | except (MultipleInstanceError, RuntimeError): 76 | return None, None # Could not determine 77 | for srv in _list_maybe_running_servers(): 78 | try: 79 | sessions = _get_sessions(srv) 80 | for sess in sessions: 81 | if sess['kernel']['id'] == kernel_id: 82 | return srv, PurePath(sess['path']) 83 | except Exception: 84 | pass # There may be stale entries in the runtime directory 85 | return None, None 86 | 87 | 88 | def name() -> str: 89 | """ Returns the short name of the notebook w/o the .ipynb extension, 90 | or raises a FileNotFoundError exception if it cannot be determined. 91 | """ 92 | _, path = _find_nb_path() 93 | if path: 94 | return path.stem 95 | raise FileNotFoundError(FILE_ERROR.format('name')) 96 | 97 | 98 | def path() -> Path: 99 | """ Returns the absolute path of the notebook, 100 | or raises a FileNotFoundError exception if it cannot be determined. 101 | """ 102 | srv, path = _find_nb_path() 103 | if srv and path: 104 | root_dir = Path(srv.get('root_dir') or srv['notebook_dir']) 105 | return root_dir / path 106 | raise FileNotFoundError(FILE_ERROR.format('path')) 107 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | from pathlib import Path 3 | 4 | here = Path(__file__).parent 5 | long_description = (here / 'README.md').read_text() 6 | 7 | setuptools.setup( 8 | name='ipynbname', 9 | version='2023.2.0.0', 10 | author='Mark McPherson', 11 | author_email='msm1089@yahoo.co.uk', 12 | description='Simply returns either notebook filename or the full path to the notebook when run from Jupyter notebook in browser.', 13 | long_description=long_description, 14 | long_description_content_type='text/markdown', 15 | license='MIT', 16 | keywords='jupyter notebook filename'.split(), 17 | url='https://github.com/msm1089/ipynbname', 18 | packages=setuptools.find_packages(), 19 | package_data={}, 20 | install_requires=['ipykernel'], 21 | python_requires='>=3.4', 22 | classifiers=[ 23 | 'Operating System :: OS Independent', 24 | 'Development Status :: 4 - Beta', 25 | 'Framework :: Jupyter', 26 | 'Topic :: Utilities', 27 | 'License :: OSI Approved :: MIT License' 28 | ] 29 | ) 30 | --------------------------------------------------------------------------------