matusko
matusko

Reputation: 3767

How to get active kernel name in Jupyter notebook

I would like to make a notebook that prints the active kernel name. I registered multiple venvs as kernels using the

python -m ipykernel install --user --name <kernel_name>

In the notebook I would like to print some metadata about the active kernel.

How can one get the name of the active kernel?


EDIT:

Here are the particular versions in my stack

ipykernel==4.5.2
ipython==5.3.0
jupyter==1.0.0

nevertheless, the question should be answered in general.

Upvotes: 8

Views: 16455

Answers (2)

Shadi
Shadi

Reputation: 10335

In jupyterlab, eduffy's comment works

import sys
import os
kernel_name = os.path.basename(sys.executable.replace("/bin/python",""))

Upvotes: 4

jakevdp
jakevdp

Reputation: 86310

One way to do this is using Javascript within the notebook, and executing some code to make the string available in Python:

%%javascript
var kernel = Jupyter.notebook.kernel
kernel.execute('kernel_name = ' + '"' + kernel.name + '"')

Then you have the kernel name in Python:

print(kernel_name)
# my-kernel

As an added bonus, you can use the jupyter_client module to find more information about the kernel once you have its name:

from jupyter_client import kernelspec
spec = kernelspec.get_kernel_spec(kernel_name)
print(spec.resource_dir)
# /path/to/my/kernel

Upvotes: 7

Related Questions