How to get active kernel name in Jupyter notebook

2019-05-24 23:11发布

问题:

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.

回答1:

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