How to get kernel state from running local jupyter notebook?

Hey, I want to get kernel state whether it is idle or busy from the local running jupyter notebook. How should I proceed? It would be best If I can get those using command line

Hereā€™s a quick approach that uses the REST API using curl:

You can get the ?token from e.g.

jupyter server list --json
2 Likes

But it is just providing the List of currently active kernels. I want to see the kernel state when the notebook is not running then I should get the idle message and when it is running I should get the busy message. Can you help me to get this?

The payload from the response includes the executIon_stateā€¦ i believe this gets cached by the server, and doesnā€™t actually make a request at that moment.

{'id': '73109856-1658-4abb-b850-6f011325eff5',
  'path': 'Untitled.ipynb',
  'name': 'Untitled.ipynb',
  'type': 'notebook',
  'kernel': {'id': '45b29d0c-3a72-416b-a964-7a04f0c637ef',
   'name': 'python3',
   'last_activity': '2022-07-21T13:39:00.822405Z',
   'execution_state': 'idle',  # <----- this
   'connections': 1},
  'notebook': {'path': 'Untitled.ipynb', 'name': 'Untitled.ipynb'}},

Otherwise, you would have to connect to the kernel, with something like this:

import jupyter_core, jupyter_client, pathlib
rt_dir = pathlib.Path(jupyter_core.paths.jupyter_runtime_dir())
cf = next(rt_dir.glob("kernel-*.json")) # do a better job of this
c = jupyter_client.AsyncKernelClient()
c.load_connection_file(cf)
msg = await c.iopub_channel.get_msg()
print(msg["content"]["execution_state"])
1 Like


I am getting this error. {ā€œmessageā€: ā€œForbiddenā€, ā€œreasonā€: null}.

Those instructions were almost certainly from a unix computerā€¦ it could be your curl doesnā€™t work the same way. You could also try in python with subprocess and urllib, which should be more portable.

1 Like

Got the required data.

Try this.
payload = {ā€˜tokenā€™: ā€˜get token from jupyter notebook listā€™}
api_url = ā€˜http://127.0.0.1:8888/api/sessionsā€™
result = requests.get(api_url,params = payload)
result.json()

perhaps a better way to grab the config file:

from IPython.core.getipython import get_ipython
kernel = get_ipython().kernel
cf=kernel.config['IPKernelApp']['connection_file']