I am trying to automatically detect whether my library is being run in classic Jupyter Notebook or JupyterLab. I know get_ipython()
can tell me whether I'm in a kernel at all, but it doesn't tell me which frontend I'm in.
Asked
Active
Viewed 756 times
8

Benjamin Lee
- 481
- 1
- 5
- 15
3 Answers
0
Perhaps you can check via whether os.getenv('JUPYTERHUB_API_TOKEN')
is None
or not.

mabraham
- 2,806
- 3
- 28
- 25
-
This variable is not even set (running a kernel from Jupyter lab) – marscher Feb 06 '23 at 09:41
0
Using psutil module....
import psutil
parent_process = psutil.Process().parent().cmdline()[-1]
if 'jupyter-lab' in parent_process:
print('You are using Jupyterlab')
elif 'jupyter-notebook' in parent_process:
print('You are using Jupyter Notebook')
else:
print('You are using something else')

DougR
- 3,196
- 1
- 28
- 29
-
I didn't find this to be 100% reliable in all situations, see [here](https://discourse.jupyter.org/t/find-out-if-my-code-runs-inside-a-notebook-or-jupyter-lab/6935/17?u=fomightez). – Wayne Aug 01 '22 at 19:13
-
This won't work for non-default Jupyter installs like "The littlest jupyter hub" for instance. – marscher Feb 06 '23 at 09:38
0
Based on @mabraham's answer I came up with the following implementation. It it detects ipykernels launched from Jupyter-lab and Jupyter-hub servers.
def is_jupyterlab_session() -> bool:
"""Check whether we are in a Jupyter-Lab session.
Notes
-----
This is a heuristic based process inspection based on the current Jupyter lab
(major 3) version. So it could fail in the future.
It will also report false positive in case a classic notebook frontend is started
via Jupyter lab.
"""
import psutil
# inspect parent process for any signs of being a jupyter lab server
parent = psutil.Process().parent()
if parent.name() == "jupyter-lab":
return True
keys = (
"JUPYTERHUB_API_KEY",
"JPY_API_TOKEN",
"JUPYTERHUB_API_TOKEN",
)
env = parent.environ()
if any(k in env for k in keys):
return True
return False

marscher
- 800
- 1
- 5
- 22