Get Base URL of Current Jupyter Server IPython is Connected To

Viewed 1551

I'd like to be able to know the base URL of the Jupyter Notebook server IPython is presently connected to. I'm aware of the notebook.notebookapp.list_running_servers() function which produces output like:

[
  {
    'base_url': '/',
    'hostname': 'localhost',
    'notebook_dir': '/home/username/dir-notebook-was-spawned-in',
    'password': False,
    'pid': 368094,
    'port': 8888,
    'secure': False,
    'sock': '',
    'token': '4e7e860527d5333306cb06c594aa2167a7d375294f96c2d9',
    'url': 'http://localhost:8888/',
  },
  ...
]

This feels tantalizingly close to what I want since there's a base_url key there, however I don't know how to determine which server in the list is where IPython is actually connected to. The closest approximation I've been able to come up with is to see which server's notebook_dir key most closely matches os.getcwd() but this is obviously imperfect.

Further Findings:

  • I've now realized that notebook.notebookapp.list_running_servers() is not the right way to go about this because the notebook server and the kernel are not guaranteed to be running in the same place and in that case the function would always return an empty list.
2 Answers

There was some discussion about it in ipyleaflet. You cannot get the base URL only from the back-end, the way we do it in ipyleaflet is to get it in the front-end using window.location.href.

On the command line you can use the following:

jupyter notebook list --json | python3 -c 'import json; import sys; print(json.load(sys.stdin)["base_url"])'

(Remove the ["base_url"] part from that command to see the full dictionary).

In Python, there is base url listed among the output of:

import psutil
psutil.Process().parent().cmdline()

These are derived from discussions on the Jupyter Discourse Forum here and here.

For Binder sessions, it was pointed out here to use the following to get a good listing of details:

env | grep -i jupyter
Related