jupyter_server.services.kernels package#



Tornado handlers for kernels.

Preliminary documentation at ipython/ipython

class jupyter_server.services.kernels.handlers.KernelActionHandler(application, request, **kwargs)#

Bases: KernelsAPIHandler

A kernel action API handler.

post(kernel_id, action)#

Interrupt or restart a kernel.

class jupyter_server.services.kernels.handlers.KernelHandler(application, request, **kwargs)#

Bases: KernelsAPIHandler

A kernel API handler.


Remove a kernel.


Get a kernel model.

class jupyter_server.services.kernels.handlers.KernelsAPIHandler(application, request, **kwargs)#

Bases: APIHandler

A kernels API handler.

auth_resource = 'kernels'#
class jupyter_server.services.kernels.handlers.MainKernelHandler(application, request, **kwargs)#

Bases: KernelsAPIHandler

The root kernel handler.


Get the list of running kernels.


Start a kernel.

A MultiKernelManager for use in the Jupyter server

  • raises HTTPErrors

  • creates REST API models

class jupyter_server.services.kernels.kernelmanager.AsyncMappingKernelManager(**kwargs: Any)#

Bases: MappingKernelManager, AsyncMultiKernelManager

An asynchronous mapping kernel manager.

class jupyter_server.services.kernels.kernelmanager.MappingKernelManager(**kwargs: Any)#

Bases: MultiKernelManager

A KernelManager that handles - File mapping - HTTP error handling - Kernel message filtering


Whether to send tracebacks to clients on exceptions.


White list of allowed kernel message types. When the list is empty, all message types are allowed.


Whether messages from kernels whose frontends have disconnected should be buffered in-memory.

When True (default), messages are buffered and replayed on reconnect, avoiding lost messages due to interrupted connectivity.

Disable if long-running kernels will produce too much output while no frontends are connected.


Whether to consider culling kernels which are busy. Only effective if cull_idle_timeout > 0.


Whether to consider culling kernels which have one or more connections. Only effective if cull_idle_timeout > 0.


Timeout (in seconds) after which a kernel is considered idle and ready to be culled. Values of 0 or lower disable culling. Very short timeouts may result in kernels being culled for users with poor network connections.


The interval (in seconds) on which to check for idle kernels exceeding the cull timeout value.

cull_interval_default = 300#
async cull_kernel_if_idle(kernel_id)#

Cull a kernel if it is idle.

async cull_kernels()#

Handle culling kernels.

cwd_for_path(path, **kwargs)#

Turn API path into absolute OS path.

get_buffer(kernel_id, session_key)#

Get the buffer for a given kernel

  • kernel_id (str) – The id of the kernel to stop buffering.

  • session_key (str, optional) – The session_key, if any, that should get the buffer. If the session_key matches the current buffered session_key, the buffer will be returned.


Start idle culler if ‘cull_idle_timeout’ is greater than zero.

Regardless of that value, set flag that we’ve been here.


An instance of a Python list.


Timeout for giving up on a kernel (in seconds).

On starting and restarting kernels, we check whether the kernel is running and responsive by sending kernel_info_requests. This sets the timeout in seconds for how long the kernel can take before being presumed dead. This affects the MappingKernelManager (which handles kernel restarts) and the ZMQChannelsHandler (which handles the startup).


Return a JSON-safe dict representing a kernel

For use in representing kernels in the JSON APIs.


The last activity on any kernel, including shutting down a kernel


Returns a list of kernel_id’s of kernels running.


Notice a new connection to a kernel


Notice a disconnection from a kernel


Used by ZMQChannelsHandler to determine how to coordinate nudge and replays.

Ports are captured when starting a kernel (via MappingKernelManager). Ports are considered changed (following restarts) if the referenced KernelManager is using a set of ports different from those captured at startup. If changes are detected, the captured set is updated and a value of True is returned.

NOTE: Use is exclusive to ZMQChannelsHandler because this object is a singleton instance while ZMQChannelsHandler instances are per WebSocket connection that can vary per kernel lifetime.

async restart_kernel(kernel_id, now=False)#

Restart a kernel by kernel_id


A trait for unicode strings.

async shutdown_kernel(kernel_id, now=False, restart=False)#

Shutdown a kernel by kernel_id

start_buffering(kernel_id, session_key, channels)#

Start buffering messages for a kernel

  • kernel_id (str) – The id of the kernel to stop buffering.

  • session_key (str) – The session_key, if any, that should get the buffer. If the session_key matches the current buffered session_key, the buffer will be returned.

  • channels (dict({'channel': ZMQStream})) – The zmq channels whose messages should be buffered.

async start_kernel(*, kernel_id=None, path=None, **kwargs)#

Start a kernel for a session and return its kernel_id.

  • kernel_id (uuid (str)) – The uuid to associate the new kernel with. If this is not None, this kernel will be persistent whenever it is requested.

  • path (API path) – The API path (unicode, ‘/’ delimited) for the cwd. Will be transformed to an OS path relative to root_dir.

  • kernel_name (str) – The name identifying which kernel spec to launch. This is ignored if an existing kernel is returned, but it may be checked in the future.

Return type:



Start watching IOPub messages on a kernel for activity.

  • update last_activity on every message

  • record execution_state from status messages


Stop buffering kernel messages


kernel_id (str) – The id of the kernel to stop buffering.


Stop watching IOPub messages on a kernel for activity.


Message to print when allow_tracebacks is False, and an exception occurs

class jupyter_server.services.kernels.kernelmanager.ServerKernelManager(*args, **kwargs)#

Bases: AsyncIOLoopKernelManager

A server-specific kernel manager.

property core_event_schema_paths: list[Path]#
emit(schema_id, data)#

Emit an event from the kernel manager.


A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute


The current execution state of the kernel

extra_event_schema_paths: List[str]#

A list of pathlib.Path objects pointing at to register with the kernel manager’s eventlogger.

async interrupt_kernel(*args, **kwargs)#

Interrupts the kernel by sending it a signal.

Unlike signal_kernel, this operation is well supported on all platforms.


The last activity on the kernel


The reason for the last failure against the kernel

async restart_kernel(*args, **kwargs)#

Restarts a kernel with the arguments that were used to launch it.

  • now (bool, optional) –

    If True, the kernel is forcefully restarted immediately, without having a chance to do any cleanup action. Otherwise the kernel is given 1s to clean up before a forceful restart is issued.

    In all cases the kernel is restarted, the only difference is whether it is given a chance to perform a clean shutdown or not.

  • newports (bool, optional) – If the old kernel was launched with random ports, this flag decides whether the same ports and connection file will be used again. If False, the same ports and connection file are used. This is the default. If True, new random port numbers are chosen and a new connection file is written. It is still possible that the newly chosen random port numbers happen to be the same as the old ones.

  • **kw (optional) – Any options specified here will overwrite those used to launch the kernel.

async shutdown_kernel(*args, **kwargs)#

Attempts to stop the kernel process cleanly.

This attempts to shutdown the kernels cleanly by:

  1. Sending it a shutdown message over the control channel.

  2. If that fails, the kernel is shutdown forcibly by sending it a signal.

  • now (bool) – Should the kernel be forcible killed now. This skips the first, nice shutdown attempt.

  • restart (bool) – Will this kernel be restarted after it is shutdown. When this is True, connection files will not be cleaned up.

async start_kernel(*args, **kwargs)#

Starts a kernel on this host in a separate process.

If random ports (port=0) are being used, this method must be called before the channels are created.


**kw (optional) – keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs).


Decorate kernel action methods to begin emitting jupyter kernel action events.

  • success_msg (str) – A formattable string that’s passed to the message field of the emitted event when the action succeeds. You can include the kernel_id, kernel_name, or action in the message using a formatted string argument, e.g. “{kernel_id} succeeded to {action}.”

  • error_msg (str) – A formattable string that’s passed to the message field of the emitted event when the action fails. You can include the kernel_id, kernel_name, or action in the message using a formatted string argument, e.g. “{kernel_id} failed to {action}.”

Return type:

Callable[..., Any]

Tornado handlers for WebSocket <-> ZMQ sockets.

class jupyter_server.services.kernels.websocket.KernelWebsocketHandler(application, request, **kwargs)#

Bases: WebSocketMixin, WebSocketHandler, JupyterHandler

The kernels websocket should connect

auth_resource = 'kernels'#
async get(kernel_id)#

Handle a get request for a kernel.


Get the socket connection options.

property kernel_websocket_connection_class#

The kernel websocket connection class.


Handle a socket closure.


Get a kernel message from the websocket and turn it into a ZMQ message.

async open(kernel_id)#

Open a kernel websocket.

async pre_get()#

Handle a pre_get.


Select the sub protocol for the socket.


Undo the set_default_headers in JupyterHandler

which doesn’t make sense for websockets

Module contents#