jupyter / jupyter_client

Jupyter protocol client APIs
https://jupyter-client.readthedocs.io
BSD 3-Clause "New" or "Revised" License
390 stars 284 forks source link

How to get kernel_id from a running Python kernel? #1004

Open fleming79 opened 10 months ago

fleming79 commented 10 months ago

I'm currently experimenting with ipylab, that uses ipywidgets for comms and am wondering if there is simple way to obtain the kernel_id in the Python kernel.

I found it can be extracted from the kernel config, but this is a bit hacky.

from IPython.core.getipython import get_ipython

ip = get_ipython()
kernel_id = (
    ip.kernel.config["IPKernelApp"]["connection_file"].rsplit("kernel-", 1)[1].removesuffix(".json")
)
cknoll commented 8 months ago

I used a similar trick:

import ipykernel
import re
kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1)

However, I think there should be a cleaner solution.