jupyter_client package#

Subpackages#

Submodules#

Adapters for Jupyter msg spec versions.

class jupyter_client.adapter.Adapter#

Bases: object

Base class for adapting messages

Override message_type(msg) methods to create adapters.

handle_reply_status_error(msg)#

This will be called instead of the regular handler

on any reply with status != ok

Return type:

Dict[str, Any]

msg_type_map: Dict[str, str] = {}#
update_header(msg)#

Update the header.

Return type:

Dict[str, Any]

update_metadata(msg)#

Update the metadata.

Return type:

Dict[str, Any]

update_msg_type(msg)#

Update the message type.

Return type:

Dict[str, Any]

class jupyter_client.adapter.V4toV5#

Bases: Adapter

Convert msg spec V4 to V5

complete_reply(msg)#

Handle a complete reply.

Return type:

Dict[str, Any]

complete_request(msg)#

Handle a complete request.

Return type:

Dict[str, Any]

display_data(msg)#

Handle display data.

Return type:

Dict[str, Any]

execute_reply(msg)#

Handle an execute reply.

Return type:

Dict[str, Any]

execute_request(msg)#

Handle an execute request.

Return type:

Dict[str, Any]

input_request(msg)#

Handle an input request.

Return type:

Dict[str, Any]

inspect_reply(msg)#

inspect_reply can’t be easily backward compatible

Return type:

Dict[str, Any]

inspect_request(msg)#

Handle an inspect request.

Return type:

Dict[str, Any]

kernel_info_reply(msg)#

Handle a kernel info reply.

Return type:

Dict[str, Any]

msg_type_map: Dict[str, str] = {'object_info_reply': 'inspect_reply', 'object_info_request': 'inspect_request', 'pyerr': 'error', 'pyin': 'execute_input', 'pyout': 'execute_result'}#
stream(msg)#

Handle a stream message.

Return type:

Dict[str, Any]

update_header(msg)#

Update the header.

Return type:

Dict[str, Any]

version = '5.0'#
class jupyter_client.adapter.V5toV4#

Bases: Adapter

Adapt msg protocol v5 to v4

complete_reply(msg)#

Handle a complete reply.

Return type:

Dict[str, Any]

complete_request(msg)#

Handle a complete request.

Return type:

Dict[str, Any]

display_data(msg)#

Handle a display data message.

Return type:

Dict[str, Any]

execute_reply(msg)#

Handle an execute reply.

Return type:

Dict[str, Any]

execute_request(msg)#

Handle an execute request.

Return type:

Dict[str, Any]

input_request(msg)#

Handle an input request.

Return type:

Dict[str, Any]

kernel_info_reply(msg)#

Handle a kernel info reply.

Return type:

Dict[str, Any]

msg_type_map: Dict[str, str] = {'error': 'pyerr', 'execute_input': 'pyin', 'execute_result': 'pyout', 'inspect_reply': 'object_info_reply', 'inspect_request': 'object_info_request'}#
object_info_reply(msg)#

inspect_reply can’t be easily backward compatible

Return type:

Dict[str, Any]

object_info_request(msg)#

Handle an object info request.

Return type:

Dict[str, Any]

stream(msg)#

Handle a stream message.

Return type:

Dict[str, Any]

update_header(msg)#

Update the header.

Return type:

Dict[str, Any]

version = '4.1'#
jupyter_client.adapter.adapt(msg, to_version=5)#

Adapt a single message to a target version

Parameters:
  • msg (dict) – A Jupyter message.

  • to_version (int, optional) – The target major version. If unspecified, adapt to the current version.

Return type:

Dict[str, Any]

Returns:

  • msg (dict) – A Jupyter message appropriate in the new version.

jupyter_client.adapter.code_to_line(code, cursor_pos)#

Turn a multiline code block and cursor position into a single line and new cursor position.

For adapting complete_ and object_info_request.

Return type:

Tuple[str, int]

jupyter_client.adapter.extract_oname_v4(code, cursor_pos)#

Reimplement token-finding logic from IPython 2.x javascript

for adapting object_info_request from v5 to v4

Return type:

str

Base classes to manage a Client’s interaction with a running kernel

class jupyter_client.channels.AsyncZMQSocketChannel(socket, session, loop=None)#

Bases: ZMQSocketChannel

A ZMQ socket in an async API

async get_msg(timeout=None)#

Gets a message if there is one that is ready.

Return type:

Dict[str, Any]

async get_msgs()#

Get all messages that are currently ready.

Return type:

List[Dict[str, Any]]

async msg_ready()#

Is there a message that has been received?

Return type:

bool

socket: Socket#
class jupyter_client.channels.HBChannel(context=None, session=None, address='')#

Bases: Thread

The heartbeat channel which monitors the kernel heartbeat.

Note that the heartbeat channel is paused by default. As long as you start this channel, the kernel manager will ensure that it is paused and un-paused as appropriate.

address = None#
call_handlers(since_last_heartbeat)#

This method is called in the ioloop thread when a message arrives.

Subclasses should override this method to handle incoming messages. It is important to remember that this method is called in the thread so that some logic must be done to ensure that the application level handlers are called in the application thread.

Return type:

None

close()#

Close the heartbeat thread.

Return type:

None

is_beating()#

Is the heartbeat running and responsive (and not paused).

Return type:

bool

pause()#

Pause the heartbeat.

Return type:

None

run()#

Run the heartbeat thread.

Return type:

None

session = None#
socket = None#
stop()#

Stop the channel’s event loop and join its thread.

Return type:

None

time_to_dead: float = 1.0#
unpause()#

Unpause the heartbeat.

Return type:

None

exception jupyter_client.channels.InvalidPortNumber#

Bases: Exception

An exception raised for an invalid port number.

class jupyter_client.channels.ZMQSocketChannel(socket, session, loop=None)#

Bases: object

A ZMQ socket wrapper

close()#

Close the socket channel.

Return type:

None

get_msg(timeout=None)#

Gets a message if there is one that is ready.

Return type:

Dict[str, Any]

get_msgs()#

Get all messages that are currently ready.

Return type:

List[Dict[str, Any]]

is_alive()#

Test whether the channel is alive.

Return type:

bool

msg_ready()#

Is there a message that has been received?

Return type:

bool

send(msg)#

Pass a message to the ZMQ socket to send

Return type:

None

start()#

Start the socket channel.

Return type:

None

stop()#

Close the socket channel.

Return type:

None

Abstract base classes for kernel client channels

class jupyter_client.channelsabc.ChannelABC#

Bases: object

A base class for all channel ABCs.

abstract is_alive()#

Test whether the channel is alive.

Return type:

bool

abstract start()#

Start the channel.

Return type:

None

abstract stop()#

Stop the channel.

Return type:

None

class jupyter_client.channelsabc.HBChannelABC#

Bases: ChannelABC

HBChannel ABC.

The docstrings for this class can be found in the base implementation:

jupyter_client.channels.HBChannel

abstract is_beating()#

Test whether the channel is beating.

Return type:

bool

abstract pause()#

Pause the heartbeat channel.

Return type:

None

abstract property time_to_dead: float#
abstract unpause()#

Unpause the heartbeat channel.

Return type:

None

Base class to manage the interaction with a running kernel

class jupyter_client.client.KernelClient(**kwargs)#

Bases: ConnectionFileMixin

Communicates with a single kernel on any host via zmq channels.

There are five channels associated with each kernel:

  • shell: for request/reply calls to the kernel.

  • iopub: for the kernel to publish results to frontends.

  • hb: for monitoring the kernel’s heartbeat.

  • stdin: for frontends to reply to raw_input calls in the kernel.

  • control: for kernel management calls to the kernel.

The messages that can be sent on these channels are exposed as methods of the client (KernelClient.execute, complete, history, etc.). These methods only send the message, they don’t wait for a reply. To get results, use e.g. get_shell_msg() to fetch messages from the shell channel.

allow_stdin: bool = True#
property channels_running: bool#

Are any of the channels created and running?

comm_info(target_name=None)#

Request comm info

Return type:

The msg_id of the message sent

complete(code, cursor_pos=None)#

Tab complete text in the kernel’s namespace.

Parameters:
  • code (str) – The context in which completion is requested. Can be anything between a variable name and an entire cell.

  • cursor_pos (int, optional) – The position of the cursor in the block of code where the completion was requested. Default: len(code)

Return type:

The msg_id of the message sent.

context#

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

property control_channel: Any#

Get the control channel object for this kernel.

control_channel_class#

A trait whose value must be a subclass of a specified class.

execute(code, silent=False, store_history=True, user_expressions=None, allow_stdin=None, stop_on_error=True)#

Execute code in the kernel.

Parameters:
  • code (str) – A string of code in the kernel’s language.

  • silent (bool, optional (default False)) – If set, the kernel will execute the code as quietly possible, and will force store_history to be False.

  • store_history (bool, optional (default True)) – If set, the kernel will store command history. This is forced to be False if silent is True.

  • user_expressions (dict, optional) – A dict mapping names to expressions to be evaluated in the user’s dict. The expression values are returned as strings formatted using repr().

  • allow_stdin (bool, optional (default self.allow_stdin)) –

    Flag for whether the kernel can send stdin requests to frontends.

    Some frontends (e.g. the Notebook) do not support stdin requests. If raw_input is called from code executed from such a frontend, a StdinNotImplementedError will be raised.

  • stop_on_error (bool, optional (default True)) – Flag whether to abort the execution queue, if an exception is encountered.

Return type:

The msg_id of the message sent.

property hb_channel: Any#

Get the hb channel object for this kernel.

hb_channel_class#

A trait whose value must be a subclass of a specified class.

history(raw=True, output=False, hist_access_type='range', **kwargs)#

Get entries from the kernel’s history list.

Parameters:
  • raw (bool) – If True, return the raw input.

  • output (bool) – If True, then return the output as well.

  • hist_access_type (str) –

    ‘range’ (fill in session, start and stop params), ‘tail’ (fill in n)

    or ‘search’ (fill in pattern param).

  • session (int) – For a range request, the session from which to get lines. Session numbers are positive integers; negative ones count back from the current session.

  • start (int) – The first line number of a history range.

  • stop (int) – The final (excluded) line number of a history range.

  • n (int) – The number of lines of history to get for a tail request.

  • pattern (str) – The glob-syntax pattern for a search request.

Return type:

The ID of the message sent.

input(string)#

Send a string of raw input to the kernel.

This should only be called in response to the kernel sending an input_request message on the stdin channel.

Return type:

The ID of the message sent.

inspect(code, cursor_pos=None, detail_level=0)#

Get metadata information about an object in the kernel’s namespace.

It is up to the kernel to determine the appropriate object to inspect.

Parameters:
  • code (str) – The context in which info is requested. Can be anything between a variable name and an entire cell.

  • cursor_pos (int, optional) – The position of the cursor in the block of code where the info was requested. Default: len(code)

  • detail_level (int, optional) – The level of detail for the introspection (0-2)

Return type:

The msg_id of the message sent.

ioloop = None#
property iopub_channel: Any#

Get the iopub channel object for this kernel.

iopub_channel_class#

A trait whose value must be a subclass of a specified class.

is_complete(code)#

Ask the kernel whether some code is complete and ready to execute.

Return type:

The ID of the message sent.

kernel_info()#

Request kernel info

Return type:

The msg_id of the message sent

property shell_channel: Any#

Get the shell channel object for this kernel.

shell_channel_class#

A trait whose value must be a subclass of a specified class.

shutdown(restart=False)#

Request an immediate kernel shutdown on the control channel.

Upon receipt of the (empty) reply, client code can safely assume that the kernel has shut down and it’s safe to forcefully terminate it if it’s still alive.

The kernel will send the reply via a function registered with Python’s atexit module, ensuring it’s truly done as the kernel is done with all normal operation.

Return type:

The msg_id of the message sent

start_channels(shell=True, iopub=True, stdin=True, hb=True, control=True)#

Starts the channels for this kernel.

This will create the channels if they do not exist and then start them (their activity runs in a thread). If port numbers of 0 are being used (random ports) then you must first call start_kernel(). If the channels have been stopped and you call this, RuntimeError will be raised.

Return type:

None

property stdin_channel: Any#

Get the stdin channel object for this kernel.

stdin_channel_class#

A trait whose value must be a subclass of a specified class.

stop_channels()#

Stops all the running channels for this kernel.

This stops their event loops and joins their threads.

Return type:

None

jupyter_client.client.reqrep(wrapped, meth, channel='shell')#
Return type:

Callable

jupyter_client.client.validate_string_dict(dct)#

Validate that the input is a dict with string keys and values.

Raises ValueError if not.

Return type:

None

Abstract base class for kernel clients

class jupyter_client.clientabc.KernelClientABC#

Bases: object

KernelManager ABC.

The docstrings for this class can be found in the base implementation:

jupyter_client.client.KernelClient

abstract property channels_running: bool#

Get whether the channels are running.

abstract property control_channel: ChannelABC#
abstract property control_channel_class: type[ChannelABC]#
abstract property hb_channel: ChannelABC#
abstract property hb_channel_class: type[ChannelABC]#
abstract property iopub_channel: ChannelABC#
abstract property iopub_channel_class: type[ChannelABC]#
abstract property kernel: Any#
abstract property shell_channel: ChannelABC#
abstract property shell_channel_class: type[ChannelABC]#
abstract start_channels(shell=True, iopub=True, stdin=True, hb=True, control=True)#

Start the channels for the client.

Return type:

None

abstract property stdin_channel: ChannelABC#
abstract property stdin_channel_class: type[ChannelABC]#
abstract stop_channels()#

Stop the channels for the client.

Return type:

None

Utilities for connecting to jupyter kernels

The ConnectionFileMixin class in this module encapsulates the logic related to writing and reading connections files.

class jupyter_client.connect.LocalPortCache(**kwargs)#

Bases: SingletonConfigurable

Used to keep track of local ports in order to prevent race conditions that can occur between port acquisition and usage by the kernel. All locally- provisioned kernels should use this mechanism to limit the possibility of race conditions. Note that this does not preclude other applications from acquiring a cached but unused port, thereby re-introducing the issue this class is attempting to resolve (minimize). See: jupyter/jupyter_client#487

find_available_port(ip)#
Return type:

int

return_port(port)#
Return type:

None

jupyter_client.connect.find_connection_file(filename='kernel-*.json', path=None, profile=None)#

find a connection file, and return its absolute path.

The current working directory and optional search path will be searched for the file if it is not given by absolute path.

If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile’s security dir with the latest access time will be used.

Parameters:
  • filename (str) – The connection file or fileglob to search for.

  • path (str or list of strs[optional]) – Paths in which to search for connection files.

Returns:

str

Return type:

The absolute path of the connection file.

jupyter_client.connect.tunnel_to_kernel(connection_info, sshserver, sshkey=None)#

tunnel connections to a kernel via ssh

This will open five SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP.

Parameters:
  • connection_info (dict or str (path)) – Either a connection dict, or the path to a JSON connection file

  • sshserver (str) – The ssh sever to use to tunnel to the kernel. Can be a full user@server:port string. ssh config aliases are respected.

  • sshkey (str [optional]) – Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host.

Return type:

tuple[Any, ...]

Returns:

  • (shell, iopub, stdin, hb, control) (ints) – The five ports on localhost that have been forwarded to the kernel.

jupyter_client.connect.write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0, control_port=0, ip='', key=b'', transport='tcp', signature_scheme='hmac-sha256', kernel_name='', **kwargs)#

Generates a JSON config file, including the selection of random ports.

Parameters:
  • fname (unicode) – The path to the file to write

  • shell_port (int, optional) – The port to use for ROUTER (shell) channel.

  • iopub_port (int, optional) – The port to use for the SUB channel.

  • stdin_port (int, optional) – The port to use for the ROUTER (raw input) channel.

  • control_port (int, optional) – The port to use for the ROUTER (control) channel.

  • hb_port (int, optional) – The port to use for the heartbeat REP channel.

  • ip (str, optional) – The ip address the kernel will bind to.

  • key (str, optional) – The Session key used for message authentication.

  • signature_scheme (str, optional) – The scheme used for message authentication. This has the form ‘digest-hash’, where ‘digest’ is the scheme used for digests, and ‘hash’ is the name of the hash function used by the digest scheme. Currently, ‘hmac’ is the only supported digest scheme, and ‘sha256’ is the default hash function.

  • kernel_name (str, optional) – The name of the kernel currently connected to.

Return type:

tuple[str, Dict[str, Union[int, str, bytes]]]

A minimal application base mixin for all ZMQ based IPython frontends.

This is not a complete console app, as subprocess will not be able to receive input, there is no real readline support, among other limitations. This is a refactoring of what used to be the IPython/qt/console/qtconsoleapp.py

class jupyter_client.consoleapp.IPythonConsoleApp(*args, **kwargs)#

Bases: JupyterConsoleApp

An app to manage an ipython console.

class jupyter_client.consoleapp.JupyterConsoleApp(**kwargs)#

Bases: ConnectionFileMixin

The base Jupyter console application.

aliases#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

build_kernel_argv(argv=None)#

build argv to be passed to kernel subprocess

Override in subclasses if any args should be passed to the kernel

Return type:

None

classes = [<class 'jupyter_client.manager.KernelManager'>, <class 'jupyter_client.restarter.KernelRestarter'>, <class 'jupyter_client.session.Session'>]#
confirm_exit#

Set to display confirmation dialog on exit. You can always use ‘exit’ or ‘quit’, to force a direct exit without any confirmation.

description: Union[str, Unicode] = '\n        The Jupyter Console Mixin.\n\n        This class contains the common portions of console client (QtConsole,\n        ZMQ-based terminal console, etc).  It is not a full console, in that\n        launched terminal subprocesses will not be able to accept input.\n\n        The Console using this mixing supports various extra features beyond\n        the single-process Terminal IPython shell, such as connecting to\n        existing kernel, via:\n\n            jupyter console <appname> --existing\n\n        as well as tunnel via SSH\n\n    '#
existing#

Connect to an already running kernel

flags#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

init_connection_file()#

find the connection file, and load the info if found.

The current working directory and the current profile’s security directory will be searched for the file if it is not given by absolute path.

When attempting to connect to an existing kernel and the –existing argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the current profile’s security dir with the latest access time will be used.

After this method is called, self.connection_file contains the full path to the connection file, never just its name.

Return type:

None

init_kernel_client()#

Initialize the kernel client.

Return type:

None

init_kernel_manager()#

Initialize the kernel manager.

Return type:

None

init_ssh()#

set up ssh tunnels, if needed.

Return type:

None

initialize(argv=None)#
Return type:

None

Classes which mix this class in should call:

JupyterConsoleApp.initialize(self,argv)

kernel_argv#

An instance of a Python list.

kernel_client_class#

alias of BlockingKernelClient

kernel_manager_class#

The kernel manager class to use.

kernel_name: str | Unicode#

The name of the default kernel to start.

name: Union[str, Unicode] = 'jupyter-console-mixin'#
sshkey#

Path to the ssh key to use for logging in to the ssh server.

sshserver#

The SSH server to use to connect to the kernel.

Utilities to manipulate JSON objects.

jupyter_client.jsonutil.date_default(obj)#

DEPRECATED: Use jupyter_client.jsonutil.json_default

Return type:

Any

jupyter_client.jsonutil.extract_dates(obj)#

extract ISO8601 dates from unpacked JSON

Return type:

Any

jupyter_client.jsonutil.json_clean(obj)#
Return type:

Any

jupyter_client.jsonutil.json_default(obj)#

default function for packing objects in JSON.

Return type:

Any

jupyter_client.jsonutil.parse_date(s)#

parse an ISO8601 date string

If it is None or not a valid ISO8601 timestamp, it will be returned unmodified. Otherwise, it will return a datetime object.

Return type:

Union[str, datetime, None]

jupyter_client.jsonutil.squash_dates(obj)#

squash datetime objects into ISO8601 strings

Return type:

Any

An application to launch a kernel by name in a local subprocess.

class jupyter_client.kernelapp.KernelApp(**kwargs)#

Bases: JupyterApp

Launch a kernel by name in a local subprocess.

aliases: StrDict = {'ip': 'KernelManager.ip', 'kernel': 'KernelApp.kernel_name'}#
classes: ClassesType = [<class 'jupyter_client.manager.KernelManager'>, <class 'jupyter_client.kernelspec.KernelSpecManager'>]#
description: str | Unicode[str, str | bytes] = 'Run a kernel locally in a subprocess'#
flags: StrDict = {'debug': ({'Application': {'log_level': 10}}, 'set log level to logging.DEBUG (maximize logging output)')}#
initialize(argv=None)#

Initialize the application.

Return type:

None

kernel_name#

The name of a kernel type to start

log_connection_info()#

Log the connection info for the kernel.

Return type:

None

setup_signals()#

Shutdown on SIGTERM or SIGINT (Ctrl-C)

Return type:

None

shutdown(signo)#

Shut down the application.

Return type:

None

start()#

Start the application.

Return type:

None

version: str | Unicode[str, str | bytes] = '8.6.1'#

Tools for managing kernel specs

class jupyter_client.kernelspec.KernelSpec(*args, **kwargs)#

Bases: HasTraits

A kernel spec model object.

argv: List[str]#

An instance of a Python list.

display_name#

A trait for unicode strings.

env#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

classmethod from_resource_dir(resource_dir)#

Create a KernelSpec object by reading kernel.json

Pass the path to the directory containing kernel.json.

Return type:

KernelSpec

interrupt_mode#

An enum of strings where the case should be ignored.

language#

A trait for unicode strings.

metadata#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

mimetype#

A trait for unicode strings.

name#

A trait for unicode strings.

resource_dir#

A trait for unicode strings.

to_dict()#

Convert the kernel spec to a dict.

Return type:

dict[str, Any]

to_json()#

Serialise this kernelspec to a JSON object.

Returns a string.

Return type:

str

class jupyter_client.kernelspec.KernelSpecManager(**kwargs)#

Bases: LoggingConfigurable

A manager for kernel specs.

allowed_kernelspecs#

List of allowed kernel names.

By default, all installed kernels are allowed.

data_dir#

A trait for unicode strings.

ensure_native_kernel#

If there is no Python kernelspec registered and the IPython kernel is available, ensure it is added to the spec list.

find_kernel_specs()#

Returns a dict mapping kernel names to resource directories.

Return type:

dict[str, str]

get_all_specs()#

Returns a dict mapping kernel names to kernelspecs.

Returns a dict of the form:

{
  'kernel_name': {
    'resource_dir': '/path/to/kernel_name',
    'spec': {"the spec itself": ...}
  },
  ...
}
Return type:

dict[str, Any]

get_kernel_spec(kernel_name)#

Returns a KernelSpec instance for the given kernel_name.

Raises NoSuchKernel if the given kernel name is not found.

Return type:

KernelSpec

install_kernel_spec(source_dir, kernel_name=None, user=False, replace=None, prefix=None)#

Install a kernel spec by copying its directory.

If kernel_name is not given, the basename of source_dir will be used.

If user is False, it will attempt to install into the systemwide kernel registry. If the process does not have appropriate permissions, an OSError will be raised.

If prefix is given, the kernelspec will be installed to PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix for installation inside virtual or conda envs.

Return type:

str

install_native_kernel_spec(user=False)#

DEPRECATED: Use ipykernel.kernelspec.install

Return type:

None

kernel_dirs: List[str]#

List of kernel directories to search. Later ones take priority over earlier.

kernel_spec_class#

The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior.

remove_kernel_spec(name)#

Remove a kernel spec directory by name.

Returns the path that was deleted.

Return type:

str

user_kernel_dir#

A trait for unicode strings.

whitelist#

Deprecated, use KernelSpecManager.allowed_kernelspecs

exception jupyter_client.kernelspec.NoSuchKernel(name)#

Bases: KeyError

An error raised when there is no kernel of a give name.

jupyter_client.kernelspec.find_kernel_specs()#

Returns a dict mapping kernel names to resource directories.

Return type:

dict[str, str]

jupyter_client.kernelspec.get_kernel_spec(kernel_name)#

Returns a KernelSpec instance for the given kernel_name.

Raises KeyError if the given kernel name is not found.

Return type:

KernelSpec

jupyter_client.kernelspec.install_kernel_spec(source_dir, kernel_name=None, user=False, replace=False, prefix=None)#

Install a kernel spec by copying its directory.

If kernel_name is not given, the basename of source_dir will be used.

If user is False, it will attempt to install into the systemwide kernel registry. If the process does not have appropriate permissions, an OSError will be raised.

If prefix is given, the kernelspec will be installed to PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix for installation inside virtual or conda envs.

Return type:

str

jupyter_client.kernelspec.install_native_kernel_spec(user=False)#

DEPRECATED: Use ipykernel.kernelspec.install

Return type:

None

Apps for managing kernel specs.

class jupyter_client.kernelspecapp.InstallKernelSpec(**kwargs)#

Bases: JupyterApp

An app to install a kernel spec.

aliases: StrDict = {'config': 'JupyterApp.config_file', 'log-level': 'Application.log_level', 'name': 'InstallKernelSpec.kernel_name', 'prefix': 'InstallKernelSpec.prefix'}#
description: str | Unicode[str, str | bytes] = 'Install a kernel specification directory.\n\n    Given a SOURCE DIRECTORY containing a kernel spec,\n    jupyter will copy that directory into one of the Jupyter kernel directories.\n    The default is to install kernelspecs for all users.\n    `--user` can be specified to install a kernel only for the current user.\n    '#
examples: str | Unicode[str, str | bytes] = '\n    jupyter kernelspec install /path/to/my_kernel --user\n    '#
flags: StrDict = {'debug': ({'Application': {'log_level': 10}}, 'set log level to logging.DEBUG (maximize logging output)'), 'replace': ({'InstallKernelSpec': {'replace': True}}, 'Replace any existing kernel spec with this name.'), 'sys-prefix': ({'InstallKernelSpec': {'prefix': '/home/docs/checkouts/readthedocs.org/user_builds/jupyter-client/envs/stable'}}, "Install to Python's sys.prefix. Useful in conda/virtual environments."), 'user': ({'InstallKernelSpec': {'user': True}}, 'Install to the per-user kernel registry')}#
kernel_name#

Install the kernel spec with this name

kernel_spec_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

parse_command_line(argv)#

Parse the command line args.

Return type:

None

prefix#

Specify a prefix to install to, e.g. an env. The kernelspec will be installed in PREFIX/share/jupyter/kernels/

replace#

Replace any existing kernel spec with this name.

sourcedir#

A trait for unicode strings.

start()#

Start the application.

Return type:

None

usage = 'jupyter kernelspec install SOURCE_DIR [--options]'#
user#

Try to install the kernel spec to the per-user directory instead of the system or environment directory.

version: str | Unicode[str, str | bytes] = '8.6.1'#
class jupyter_client.kernelspecapp.InstallNativeKernelSpec(**kwargs)#

Bases: JupyterApp

An app to install the native kernel spec.

description: str | Unicode[str, str | bytes] = '[DEPRECATED] Install the IPython kernel spec directory for this Python.'#
flags: StrDict = {'debug': ({'Application': {'log_level': 10}}, 'set log level to logging.DEBUG (maximize logging output)'), 'user': ({'InstallNativeKernelSpec': {'user': True}}, 'Install to the per-user kernel registry')}#
kernel_spec_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

start()#

Start the application.

Return type:

None

user#

Try to install the kernel spec to the per-user directory instead of the system or environment directory.

version: str | Unicode[str, str | bytes] = '8.6.1'#
class jupyter_client.kernelspecapp.KernelSpecApp(**kwargs)#

Bases: Application

An app to manage kernel specs.

aliases: StrDict = {}#
description: str | Unicode[str, str | bytes] = 'Manage Jupyter kernel specifications.'#
flags: StrDict = {}#
name: str | Unicode[str, str | bytes] = 'jupyter kernelspec'#
start()#

Start the application.

Return type:

None

subcommands: dict[str, t.Any] | Dict[str, t.Any]#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

version: str | Unicode[str, str | bytes] = '8.6.1'#
class jupyter_client.kernelspecapp.ListKernelSpecs(**kwargs)#

Bases: JupyterApp

An app to list kernel specs.

description: str | Unicode[str, str | bytes] = 'List installed kernel specifications.'#
flags: StrDict = {'debug': ({'Application': {'log_level': 10}}, 'set log level to logging.DEBUG (maximize logging output)'), 'json': ({'ListKernelSpecs': {'json_output': True}}, 'output spec name and location as machine-readable json.')}#
json_output#

output spec name and location as machine-readable json.

kernel_spec_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

start()#

Start the application.

Return type:

dict[str, Any] | None

version: str | Unicode[str, str | bytes] = '8.6.1'#
class jupyter_client.kernelspecapp.ListProvisioners(**kwargs)#

Bases: JupyterApp

An app to list provisioners.

description: str | Unicode[str, str | bytes] = 'List available provisioners for use in kernel specifications.'#
start()#

Start the application.

Return type:

None

version: str | Unicode[str, str | bytes] = '8.6.1'#
class jupyter_client.kernelspecapp.RemoveKernelSpec(**kwargs)#

Bases: JupyterApp

An app to remove a kernel spec.

description: str | Unicode[str, str | bytes] = 'Remove one or more Jupyter kernelspecs by name.'#
examples: str | Unicode[str, str | bytes] = 'jupyter kernelspec remove python2 [my_kernel ...]'#
flags: StrDict = {'debug': ({'Application': {'log_level': 10}}, 'set log level to logging.DEBUG (maximize logging output)'), 'f': ({'RemoveKernelSpec': {'force': True}}, "Force removal, don't prompt for confirmation."), 'generate-config': ({'JupyterApp': {'generate_config': True}}, 'generate default config file'), 'show-config': ({'Application': {'show_config': True}}, "Show the application's configuration (human-readable format)"), 'show-config-json': ({'Application': {'show_config_json': True}}, "Show the application's configuration (json format)"), 'y': ({'JupyterApp': {'answer_yes': True}}, 'Answer yes to any questions instead of prompting.')}#
force#

Force removal, don’t prompt for confirmation.

kernel_spec_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

parse_command_line(argv)#

Parse the command line args.

Return type:

None

spec_names#

An instance of a Python list.

start()#

Start the application.

Return type:

None

version: str | Unicode[str, str | bytes] = '8.6.1'#

Utilities for launching kernels

jupyter_client.launcher.launch_kernel(cmd, stdin=None, stdout=None, stderr=None, env=None, independent=False, cwd=None, **kw)#

Launches a localhost kernel, binding to the specified ports.

Parameters:
  • cmd (Popen list,) – A string of Python code that imports and executes a kernel entry point.

  • stdin (optional (default None)) – Standards streams, as defined in subprocess.Popen.

  • stdout (optional (default None)) – Standards streams, as defined in subprocess.Popen.

  • stderr (optional (default None)) – Standards streams, as defined in subprocess.Popen.

  • env (dict, optional) – Environment variables passed to the kernel

  • independent (bool, optional (default False)) – If set, the kernel process is guaranteed to survive if this process dies. If not set, an effort is made to ensure that the kernel is killed when this process dies. Note that in this case it is still good practice to kill kernels manually before exiting.

  • cwd (path, optional) – The working dir of the kernel process (default: cwd of this process).

  • **kw (optional) – Additional arguments for Popen

Return type:

Popen

Returns:

  • Popen instance for the kernel subprocess

Utilities for identifying local IP addresses.

exception jupyter_client.localinterfaces.NoIPAddresses#

Bases: Exception

jupyter_client.localinterfaces.is_local_ip(*args, **kwargs)#
Return type:

Any

jupyter_client.localinterfaces.is_public_ip(*args, **kwargs)#
Return type:

Any

jupyter_client.localinterfaces.local_ips(*args, **kwargs)#
Return type:

Any

jupyter_client.localinterfaces.localhost(*args, **kwargs)#
Return type:

Any

jupyter_client.localinterfaces.public_ips(*args, **kwargs)#
Return type:

Any

Base class to manage a running kernel

class jupyter_client.manager.AsyncKernelManager(*args, **kwargs)#

Bases: KernelManager

An async kernel manager.

async cleanup_resources(restart=False)#

Clean up resources when the kernel is shut down

Return type:

None

client(**kwargs)#

Get a client for the manager.

Return type:

AsyncKernelClient

client_class: DottedObjectName#

A string holding a valid dotted object name in Python, such as A.b3._c

client_factory: Type#

A trait whose value must be a subclass of a specified class.

context: Instance#

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

async finish_shutdown(waittime=None, pollinterval=0.1, restart=False)#

Wait for kernel shutdown, then kill process if it doesn’t shutdown.

This does not send shutdown requests - use request_shutdown() first.

Return type:

None

async interrupt_kernel()#

Interrupts the kernel by sending it a signal.

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

Return type:

None

async is_alive()#

Is the kernel process still running?

Return type:

bool

async post_start_kernel(**kw)#

Performs any post startup tasks relative to the kernel.

Parameters:

**kw (optional) – keyword arguments that were used in the kernel process’s launch.

Return type:

None

async pre_start_kernel(**kw)#

Prepares a kernel for startup in a separate process.

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

Parameters:

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

Return type:

Tuple[List[str], Dict[str, Any]]

async request_shutdown(restart=False)#

Send a shutdown request via control channel

Return type:

None

async restart_kernel(now=False, newports=False, **kw)#

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

Parameters:
  • 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.

Return type:

None

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

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.

Parameters:
  • 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.

Return type:

None

async signal_kernel(signum)#

Sends a signal to the process group of the kernel (this usually includes the kernel and any subprocesses spawned by the kernel).

Note that since only SIGTERM is supported on Windows, this function is only useful on Unix systems.

Return type:

None

async start_kernel(**kw)#

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.

Parameters:

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

Return type:

None

class jupyter_client.manager.KernelManager(*args, **kwargs)#

Bases: ConnectionFileMixin

Manages a single kernel in a subprocess on this host.

This version starts kernels with Popen.

add_restart_callback(callback, event='restart')#

Register a callback to be called when a kernel is restarted

Return type:

None

autorestart: Bool#

Should we autorestart the kernel if it dies.

cache_ports: Bool#

True if the MultiKernelManager should cache ports for this KernelManager instance

cleanup_resources(**kwargs: Any) Any#

Clean up resources when the kernel is shut down

Return type:

Any

client(**kwargs)#

Create a client configured to connect to our kernel

Return type:

BlockingKernelClient

client_class: DottedObjectName#

A string holding a valid dotted object name in Python, such as A.b3._c

client_factory: Type#

A trait whose value must be a subclass of a specified class.

context: Instance#

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

finish_shutdown(**kwargs: Any) Any#

Wait for kernel shutdown, then kill process if it doesn’t shutdown.

This does not send shutdown requests - use request_shutdown() first.

Return type:

Any

format_kernel_cmd(extra_arguments=None)#

Replace templated args (e.g. {connection_file})

Return type:

List[str]

property has_kernel: bool#

Has a kernel process been started that we are actively managing.

interrupt_kernel(**kwargs: Any) Any#

Interrupts the kernel by sending it a signal.

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

Return type:

Any

property ipykernel: bool#
is_alive(**kwargs: Any) Any#

Is the kernel process still running?

Return type:

Any

kernel_id: Union[str, Unicode]#

A trait for unicode strings.

kernel_name: Union[str, Unicode]#

A trait for unicode strings.

property kernel_spec: KernelSpec | None#
kernel_spec_manager: Instance#

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

property owns_kernel: bool#
post_start_kernel(**kwargs: Any) Any#

Performs any post startup tasks relative to the kernel.

Parameters:

**kw (optional) – keyword arguments that were used in the kernel process’s launch.

Return type:

Any

pre_start_kernel(**kwargs: Any) Any#

Prepares a kernel for startup in a separate process.

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

Parameters:

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

Return type:

Any

provisioner: Optional[KernelProvisionerBase] = None#
property ready: Future | Future#

A future that resolves when the kernel process has started for the first time

remove_restart_callback(callback, event='restart')#

Unregister a callback to be called when a kernel is restarted

Return type:

None

request_shutdown(**kwargs: Any) Any#

Send a shutdown request via control channel

Return type:

Any

restart_kernel(**kwargs: Any) Any#

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

Parameters:
  • 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.

Return type:

Any

shutdown_kernel(**kwargs: Any) Any#

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.

Parameters:
  • 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.

Return type:

Any

shutdown_wait_time: Float#

Time to wait for a kernel to terminate before killing it, in seconds. When a shutdown request is initiated, the kernel will be immediately sent an interrupt (SIGINT), followedby a shutdown_request message, after 1/2 of shutdown_wait_time`it will be sent a terminate (SIGTERM) request, and finally at the end of `shutdown_wait_time will be killed (SIGKILL). terminate and kill may be equivalent on windows. Note that this value can beoverridden by the in-use kernel provisioner since shutdown times mayvary by provisioned environment.

shutting_down: bool = False#
signal_kernel(**kwargs: Any) Any#

Sends a signal to the process group of the kernel (this usually includes the kernel and any subprocesses spawned by the kernel).

Note that since only SIGTERM is supported on Windows, this function is only useful on Unix systems.

Return type:

Any

start_kernel(**kwargs: Any) Any#

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.

Parameters:

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

Return type:

Any

start_restarter()#

Start the kernel restarter.

Return type:

None

stop_restarter()#

Stop the kernel restarter.

Return type:

None

update_env(*, env)#

Allow to update the environment of a kernel manager.

This will take effect only after kernel restart when the new env is passed to the new kernel.

This is useful as some of the information of the current kernel reflect the state of the session that started it, and those session information (like the attach file path, or name), are mutable. :rtype: None

jupyter_client.manager.in_pending_state(method)#

Sets the kernel to a pending state by creating a fresh Future for the KernelManager’s ready attribute. Once the method is finished, set the Future’s results.

Return type:

TypeVar(F, bound= Callable[..., Any])

jupyter_client.manager.run_kernel(**kwargs)#

Context manager to create a kernel in a subprocess.

The kernel is shut down when the context exits.

Returns:

kernel_client

Return type:

connected KernelClient instance

async jupyter_client.manager.start_new_async_kernel(startup_timeout=60, kernel_name='python', **kwargs)#

Start a new kernel, and return its Manager and Client

Return type:

Tuple[AsyncKernelManager, AsyncKernelClient]

jupyter_client.manager.start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs)#

Start a new kernel, and return its Manager and Client

Return type:

Tuple[KernelManager, BlockingKernelClient]

Abstract base class for kernel managers.

class jupyter_client.managerabc.KernelManagerABC#

Bases: object

KernelManager ABC.

The docstrings for this class can be found in the base implementation:

jupyter_client.manager.KernelManager

abstract property has_kernel: bool#
abstract interrupt_kernel()#

Interrupt the kernel.

Return type:

None

abstract is_alive()#

Test whether the kernel is alive.

Return type:

bool

abstract property kernel: Any#
abstract restart_kernel(now=False, **kw)#

Restart the kernel.

Return type:

None

abstract shutdown_kernel(now=False, restart=False)#

Shut down the kernel.

Return type:

None

abstract signal_kernel(signum)#

Send a signal to the kernel.

Return type:

None

abstract start_kernel(**kw)#

Start the kernel.

Return type:

None

A kernel manager for multiple kernels

class jupyter_client.multikernelmanager.AsyncMultiKernelManager(*args, **kwargs)#

Bases: MultiKernelManager

context#

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

kernel_manager_class#

The kernel manager class. This is configurable to allow subclassing of the AsyncKernelManager for customized behavior.

async restart_kernel(kernel_id, now=False)#

Restart a kernel by its uuid, keeping the same ports.

Parameters:
  • kernel_id (uuid) – The id of the kernel to interrupt.

  • 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.

Return type:

None

async shutdown_all(now=False)#

Shutdown all kernels.

Return type:

None

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

Shutdown a kernel by its kernel uuid.

Parameters:
  • kernel_id (uuid) – The id of the kernel to shutdown.

  • now (bool) – Should the kernel be shutdown forcibly using a signal.

  • restart (bool) – Will the kernel be restarted?

Return type:

None

async start_kernel(*, kernel_name=None, **kwargs)#

Start a new kernel.

The caller can pick a kernel_id by passing one in as a keyword arg, otherwise one will be generated using new_kernel_id().

The kernel ID for the newly started kernel is returned.

Return type:

str

use_pending_kernels#

Whether to make kernels available before the process has started. The kernel has a .ready future which can be awaited before connecting

exception jupyter_client.multikernelmanager.DuplicateKernelError#

Bases: Exception

class jupyter_client.multikernelmanager.MultiKernelManager(*args, **kwargs)#

Bases: LoggingConfigurable

A class for managing multiple kernels.

add_restart_callback(kernel_id, callback, event='restart')#

add a callback for the KernelRestarter

Return type:

None

cleanup_resources(kernel_id, restart=False)#

Clean up a kernel’s resources

Return type:

None

connect_control(kernel_id, identity=None)#

Return a zmq Socket connected to the control channel.

Parameters:
  • kernel_id (uuid) – The id of the kernel

  • identity (bytes (optional)) – The zmq identity of the socket

Returns:

stream

Return type:

zmq Socket or ZMQStream

connect_hb(kernel_id, identity=None)#

Return a zmq Socket connected to the hb channel.

Parameters:
  • kernel_id (uuid) – The id of the kernel

  • identity (bytes (optional)) – The zmq identity of the socket

Returns:

stream

Return type:

zmq Socket or ZMQStream

connect_iopub(kernel_id, identity=None)#

Return a zmq Socket connected to the iopub channel.

Parameters:
  • kernel_id (uuid) – The id of the kernel

  • identity (bytes (optional)) – The zmq identity of the socket

Returns:

stream

Return type:

zmq Socket or ZMQStream

connect_shell(kernel_id, identity=None)#

Return a zmq Socket connected to the shell channel.

Parameters:
  • kernel_id (uuid) – The id of the kernel

  • identity (bytes (optional)) – The zmq identity of the socket

Returns:

stream

Return type:

zmq Socket or ZMQStream

connect_stdin(kernel_id, identity=None)#

Return a zmq Socket connected to the stdin channel.

Parameters:
  • kernel_id (uuid) – The id of the kernel

  • identity (bytes (optional)) – The zmq identity of the socket

Returns:

stream

Return type:

zmq Socket or ZMQStream

connection_dir#

A trait for unicode strings.

context#

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

default_kernel_name#

The name of the default kernel to start

external_connection_dir#

A trait for unicode strings.

finish_shutdown(kernel_id, waittime=None, pollinterval=0.1)#

Wait for a kernel to finish shutting down, and kill it if it doesn’t

Return type:

None

get_connection_info(kernel_id)#

Return a dictionary of connection data for a kernel.

Parameters:

kernel_id (uuid) – The id of the kernel.

Returns:

connection_dict – A dict of the information needed to connect to a kernel. This includes the ip address and the integer port numbers of the different channels (stdin_port, iopub_port, shell_port, hb_port).

Return type:

dict

get_kernel(kernel_id)#

Get the single KernelManager object for a kernel by its uuid.

Parameters:

kernel_id (uuid) – The id of the kernel.

Return type:

KernelManager

interrupt_kernel(kernel_id)#

Interrupt (SIGINT) the kernel by its uuid.

Parameters:

kernel_id (uuid) – The id of the kernel to interrupt.

Return type:

None

is_alive(kernel_id)#

Is the kernel alive.

This calls KernelManager.is_alive() which calls Popen.poll on the actual kernel subprocess.

Parameters:

kernel_id (uuid) – The id of the kernel.

Return type:

bool

kernel_manager_class#

The kernel manager class. This is configurable to allow subclassing of the KernelManager for customized behavior.

kernel_manager_factory#

this is kernel_manager_class after import

kernel_spec_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

list_kernel_ids()#

Return a list of the kernel ids of the active kernels.

Return type:

list[str]

new_kernel_id(**kwargs)#

Returns the id to associate with the kernel for this request. Subclasses may override this method to substitute other sources of kernel ids. :type kwargs: Any :param kwargs: :rtype: str :return: string-ized version 4 uuid

pre_start_kernel(kernel_name, kwargs)#
Return type:

tuple[KernelManager, str, str]

remove_kernel(kernel_id)#

remove a kernel from our mapping.

Mainly so that a kernel can be removed if it is already dead, without having to call shutdown_kernel.

The kernel object is returned, or None if not found.

Return type:

KernelManager

remove_restart_callback(kernel_id, callback, event='restart')#

remove a callback for the KernelRestarter

Return type:

None

request_shutdown(kernel_id, restart=False)#

Ask a kernel to shut down by its kernel uuid

Return type:

None

restart_kernel(**kwargs: Any) Any#

Restart a kernel by its uuid, keeping the same ports.

Parameters:
  • kernel_id (uuid) – The id of the kernel to interrupt.

  • 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.

Return type:

Any

shared_context#

Share a single zmq.Context to talk to all my kernels

shutdown_all(**kwargs: Any) Any#

Shutdown all kernels.

Return type:

Any

shutdown_kernel(**kwargs: Any) Any#

Shutdown a kernel by its kernel uuid.

Parameters:
  • kernel_id (uuid) – The id of the kernel to shutdown.

  • now (bool) – Should the kernel be shutdown forcibly using a signal.

  • restart (bool) – Will the kernel be restarted?

Return type:

Any

signal_kernel(kernel_id, signum)#

Sends a signal to the kernel by its uuid.

Note that since only SIGTERM is supported on Windows, this function is only useful on Unix systems.

Parameters:
  • kernel_id (uuid) – The id of the kernel to signal.

  • signum (int) – Signal number to send kernel.

Return type:

None

start_kernel(**kwargs: Any) Any#

Start a new kernel.

The caller can pick a kernel_id by passing one in as a keyword arg, otherwise one will be generated using new_kernel_id().

The kernel ID for the newly started kernel is returned.

Return type:

Any

update_env(*, kernel_id, env)#

Allow to update the environment of the given kernel.

Forward the update env request to the corresponding kernel. :rtype: None

jupyter_client.multikernelmanager.kernel_method(f)#

decorator for proxying MKM.method(kernel_id) to individual KMs by ID

Return type:

Callable

A basic kernel monitor with autorestarting.

This watches a kernel’s state using KernelManager.is_alive and auto restarts the kernel if it dies.

It is an incomplete base class, and must be subclassed.

class jupyter_client.restarter.KernelRestarter(**kwargs)#

Bases: LoggingConfigurable

Monitor and autorestart a kernel.

add_callback(f, event='restart')#

register a callback to fire on a particular event

Possible values for event: :rtype: None

‘restart’ (default): kernel has died, and will be restarted. ‘dead’: restart has failed, kernel will be left dead.

callbacks#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

debug#

Whether to include every poll event in debugging output.

Has to be set explicitly, because there will be a lot of output.

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

poll()#
Return type:

None

random_ports_until_alive#

Whether to choose new random ports when restarting before the kernel is alive.

remove_callback(f, event='restart')#

unregister a callback to fire on a particular event

Possible values for event: :rtype: None

‘restart’ (default): kernel has died, and will be restarted. ‘dead’: restart has failed, kernel will be left dead.

restart_limit#

The number of consecutive autorestarts before the kernel is presumed dead.

stable_start_time#

The time in seconds to consider the kernel to have completed a stable start up.

start()#

Start the polling of the kernel.

Return type:

None

stop()#

Stop the kernel polling.

Return type:

None

time_to_dead#

Kernel heartbeat interval in seconds.

A Jupyter console app to run files.

class jupyter_client.runapp.RunApp(**kwargs)#

Bases: JupyterApp, JupyterConsoleApp

An Jupyter Console app to run files.

aliases: StrDict#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

description: str | Unicode[str, str | bytes] = 'Run Jupyter kernel code.'#
flags: StrDict#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

frontend_aliases#

A trait which allows any value.

frontend_flags#

A trait which allows any value.

handle_sigint(*args)#

Handle SIGINT.

Return type:

None

init_kernel_info()#

Wait for a kernel to be ready, and store kernel info

Return type:

None

initialize(argv=None)#

Initialize the app.

Return type:

None

kernel_timeout#

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

On first connect and restart, the console tests 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.

name: str | Unicode[str, str | bytes] = 'jupyter run'#
parse_command_line(argv=None)#

Parse the command line arguments.

Return type:

None

start()#

Start the application.

Return type:

None

version: str | Unicode[str, str | bytes] = '8.6.1'#

Session object for building, serializing, sending, and receiving messages.

The Session object supports serialization, HMAC signatures, and metadata on messages.

Also defined here are utilities for working with Sessions: * A SessionFactory to be used as a base class for configurables that work with Sessions. * A Message object for convenience that allows attribute-access to the msg dict.

class jupyter_client.session.Message(msg_dict)#

Bases: object

A simple message object that maps dict keys to attributes.

A Message can be created from a dict and a dict from a Message instance simply by calling dict(msg_obj).

class jupyter_client.session.Session(**kwargs)#

Bases: Configurable

Object for handling serialization and sending of messages.

The Session object handles building messages and sending them with ZMQ sockets or ZMQStream objects. Objects can communicate with each other over the network via Session objects, and only need to work with the dict-based IPython message spec. The Session will handle serialization/deserialization, security, and metadata.

Sessions support configurable serialization via packer/unpacker traits, and signing with HMAC digests via the key/keyfile traits.

Parameters:
  • debug (bool) – whether to trigger extra debugging statements

  • packer/unpacker (str : 'json', 'pickle' or import_string) –

    importstrings for methods to serialize message parts. If just ‘json’ or ‘pickle’, predefined JSON and pickle packers will be used. Otherwise, the entire importstring must be used.

    The functions must accept at least valid JSON input, and output bytes.

    For example, to use msgpack: packer = ‘msgpack.packb’, unpacker=’msgpack.unpackb’

  • pack/unpack (callables) – You can also set the pack/unpack callables for serialization directly.

  • session (bytes) – the ID of this Session object. The default is to generate a new UUID.

  • username (unicode) – username added to message headers. The default is to ask the OS.

  • key (bytes) – The key used to initialize an HMAC signature. If unset, messages will not be signed or checked.

  • keyfile (filepath) – The file containing a key. If this is set, key will be initialized to the contents of the file.

adapt_version#

An int trait.

auth#

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

bsession#

A casting version of the byte string trait.

buffer_threshold#

Threshold (in bytes) beyond which an object’s buffer should be extracted to avoid pickling.

check_pid#

Whether to check PID to protect against calls after fork.

This check can be disabled if fork-safety is handled elsewhere.

clone()#

Create a copy of this Session

Useful when connecting multiple times to a given kernel. This prevents a shared digest_history warning about duplicate digests due to multiple connections to IOPub in the same process. :rtype: Session

New in version 5.1.

copy_threshold#

Threshold (in bytes) beyond which a buffer should be sent without copying.

debug#

Debug output in the Session

deserialize(msg_list, content=True, copy=True)#

Unserialize a msg_list to a nested message dict.

This is roughly the inverse of serialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list.

Parameters:
  • msg_list (list of bytes or Message objects) – The list of message parts of the form [HMAC,p_header,p_parent, p_metadata,p_content,buffer1,buffer2,…].

  • content (bool (True)) – Whether to unpack the content dict (True), or leave it packed (False).

  • copy (bool (True)) – Whether msg_list contains bytes (True) or the non-copying Message objects in each place (False).

Returns:

msg – The nested message dict with top-level keys [header, parent_header, content, buffers]. The buffers are returned as memoryviews.

Return type:

dict

digest_history#

An instance of a Python set.

digest_history_size#

The maximum number of digests to remember.

The digest history will be culled when it exceeds this value.

digest_mod#

A trait which allows any value.

feed_identities(msg_list, copy=True)#

Split the identities from the rest of the message.

Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly.

Parameters:
  • msg_list (a list of Message or bytes objects) – The message to be split.

  • copy (bool) – flag determining whether the arguments are bytes or Messages

Returns:

(idents, msg_list) – idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,…] and should be unpackable/unserializable via self.deserialize at this point.

Return type:

two lists

item_threshold#

The maximum number of items for a container to be introspected for custom serialization. Containers larger than this are pickled outright.

key#

execution key, for signing messages.

keyfile#

path to file containing execution key.

message_count = 0#
metadata#

Metadata dictionary, which serves as the default top-level metadata dict for each message.

msg(msg_type, content=None, parent=None, header=None, metadata=None)#

Return the nested message dict.

This format is different from what is sent over the wire. The serialize/deserialize methods converts this nested message dict to the wire format, which is a list of message parts.

Return type:

dict[str, Any]

msg_header(msg_type)#

Create a header for a message type.

Return type:

dict[str, Any]

property msg_id: str#
pack#

A trait which allows any value.

packer#

The name of the packer for serializing messages. Should be one of ‘json’, ‘pickle’, or an import name for a custom callable serializer.

pid#

An int trait.

recv(socket, mode=Flag.DONTWAIT, content=True, copy=True)#

Receive and unpack a message.

Parameters:

socket (ZMQStream or Socket) – The socket or stream to use in receiving.

Returns:

[idents] is a list of idents and msg is a nested message dict of same format as self.msg returns.

Return type:

[idents], msg

send(stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, track=False, header=None, metadata=None)#

Build and send a message via stream or socket.

The message format used by this function internally is as follows:

[ident1,ident2,…,DELIM,HMAC,p_header,p_parent,p_content,

buffer1,buffer2,…]

The serialize/deserialize methods convert the nested message dict into this format.

Parameters:
  • stream (zmq.Socket or ZMQStream) – The socket-like object used to send the data.

  • msg_or_type (str or Message/dict) – Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header.

  • content (dict or None) – The content of the message (ignored if msg_or_type is a message).

  • header (dict or None) – The header dict for the message (ignored if msg_to_type is a message).

  • parent (Message or dict or None) – The parent or parent header describing the parent of this message (ignored if msg_or_type is a message).

  • ident (bytes or list of bytes) – The zmq.IDENTITY routing path.

  • metadata (dict or None) – The metadata describing the message

  • buffers (list or None) – The already-serialized buffers to be appended to the message.

  • track (bool) – Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages.

Returns:

msg – The constructed message.

Return type:

dict

send_raw(stream, msg_list, flags=0, copy=True, ident=None)#

Send a raw message via ident path.

This method is used to send a already serialized message.

Parameters:
  • stream (ZMQStream or Socket) – The ZMQ stream or socket to use for sending the message.

  • msg_list (list) – The serialized list of messages to send. This only includes the [p_header,p_parent,p_metadata,p_content,buffer1,buffer2,…] portion of the message.

  • ident (ident or list) – A single ident or a list of idents to use in sending.

Return type:

None

serialize(msg, ident=None)#

Serialize the message components to bytes.

This is roughly the inverse of deserialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list.

Parameters:

msg (dict or Message) – The next message dict as returned by the self.msg method.

Returns:

msg_list

The list of bytes objects to be sent with the format:

[ident1, ident2, ..., DELIM, HMAC, p_header, p_parent,
 p_metadata, p_content, buffer1, buffer2, ...]

In this list, the p_* entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings.

Return type:

list

session#

The UUID identifying this session.

sign(msg_list)#

Sign a message with HMAC digest. If no auth, return b’’.

Parameters:

msg_list (list) – The [p_header,p_parent,p_content] part of the message list.

Return type:

bytes

signature_scheme#

The digest scheme used to construct the message signatures. Must have the form ‘hmac-HASH’.

unpack#

A trait which allows any value.

unpacker#

The name of the unpacker for unserializing messages. Only used with custom functions for packer.

unserialize(*args, **kwargs)#

DEPRECATED Use deserialize instead.

Return type:

dict[str, Any]

username#

Username for the Session. Default is your system username.

class jupyter_client.session.SessionFactory(**kwargs)#

Bases: LoggingConfigurable

The Base class for configurables that have a Session, Context, logger, and IOLoop.

context#

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

logname#

A trait for unicode strings.

loop#

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

session#

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

jupyter_client.session.default_packer(obj)#

Convert a json object to a bytes.

Return type:

bytes

jupyter_client.session.default_secure(cfg)#

Set the default behavior for a config environment to be secure.

If Session.key/keyfile have not been set, set Session.key to a new random UUID.

Return type:

None

jupyter_client.session.default_unpacker(s)#

Convert a json bytes or string to an object.

Return type:

Any

jupyter_client.session.extract_header(msg_or_header)#

Given a message or header, return the header.

Return type:

dict[str, Any]

jupyter_client.session.json_packer(obj)#

Convert a json object to a bytes.

Return type:

bytes

jupyter_client.session.json_unpacker(s)#

Convert a json bytes or string to an object.

Return type:

Any

jupyter_client.session.msg_header(msg_id, msg_type, username, session)#

Create a new message header

Return type:

dict[str, Any]

jupyter_client.session.new_id()#

Generate a new random id.

Avoids problematic runtime import in stdlib uuid on Python 2.

Return type:

str

Returns:

  • id string (16 random bytes as hex-encoded text, chunks separated by ‘-‘)

jupyter_client.session.new_id_bytes()#

Return new_id as ascii bytes

Return type:

bytes

jupyter_client.session.pickle_packer(o)#

Pack an object using the pickle module.

Return type:

bytes

jupyter_client.session.squash_unicode(obj)#

coerce unicode back to bytestrings.

Return type:

Any

jupyter_client.session.utcnow()#

Return timezone-aware UTC timestamp

Return type:

datetime

Defines a KernelClient that provides thread-safe sockets with async callbacks on message replies.

class jupyter_client.threaded.IOLoopThread#

Bases: Thread

Run a pyzmq ioloop in a thread to send and receive messages

close()#

Close the io loop thread.

Return type:

None

ioloop = None#
run()#

Run my loop, ignoring EINTR events in the poller

Return type:

None

start()#

Start the IOLoop thread

Don’t return until self.ioloop is defined, which is created in the thread

Return type:

None

stop()#

Stop the channel’s event loop and join its thread.

This calls join() and returns when the thread terminates. RuntimeError will be raised if start() is called again.

Return type:

None

class jupyter_client.threaded.ThreadedKernelClient(**kwargs)#

Bases: KernelClient

A KernelClient that provides thread-safe sockets with async callbacks on message replies.

control_channel_class#

A trait whose value must be a subclass of a specified class.

hb_channel_class#

A trait whose value must be a subclass of a specified class.

property ioloop: IOLoop | None#
ioloop_thread#

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

iopub_channel_class#

A trait whose value must be a subclass of a specified class.

is_alive()#

Is the kernel process still running?

Return type:

bool

shell_channel_class#

A trait whose value must be a subclass of a specified class.

start_channels(shell=True, iopub=True, stdin=True, hb=True, control=True)#

Start the channels on the client.

Return type:

None

stdin_channel_class#

A trait whose value must be a subclass of a specified class.

stop_channels()#

Stop the channels on the client.

Return type:

None

class jupyter_client.threaded.ThreadedZMQSocketChannel(socket, session, loop)#

Bases: object

A ZMQ socket invoking a callback in the ioloop

call_handlers(msg)#

This method is called in the ioloop thread when a message arrives.

Subclasses should override this method to handle incoming messages. It is important to remember that this method is called in the thread so that some logic must be done to ensure that the application level handlers are called in the application thread.

Return type:

None

close()#

Close the channel.

Return type:

None

flush(timeout=1.0)#

Immediately processes all pending messages on this channel.

This is only used for the IOPub channel.

Callers should use this method to ensure that call_handlers() has been called for all messages that have been received on the 0MQ SUB socket of this channel.

This method is thread safe.

Parameters:

timeout (float, optional) – The maximum amount of time to spend flushing, in seconds. The default is one second.

Return type:

None

ioloop = None#
is_alive()#

Whether the channel is alive.

Return type:

bool

process_events()#

Subclasses should override this with a method processing any pending GUI events.

Return type:

None

send(msg)#

Queue a message to be sent from the IOLoop’s thread.

Parameters:
  • msg (message to send) –

  • threadsafe (This is) –

  • loop's (as it uses IOLoop.add_callback to give the) –

  • action. (thread control of the) –

Return type:

None

session = None#
socket = None#
start()#

Start the channel.

Return type:

None

stop()#

Stop the channel.

Return type:

None

stream = None#

utils: - provides utility wrappers to run asynchronous functions in a blocking environment. - vendor functions from ipython_genutils that should be retired at some point.

Use a Windows event to interrupt a child process like SIGINT.

The child needs to explicitly listen for this - see ipykernel.parentpoller.ParentPollerWindows for a Python implementation.

jupyter_client.win_interrupt.create_interrupt_event()#

Create an interrupt event handle.

The parent process should call this to create the interrupt event that is passed to the child process. It should store this handle and use it with send_interrupt to interrupt the child process.

Return type:

Any

jupyter_client.win_interrupt.send_interrupt(interrupt_handle)#

Sends an interrupt event using the specified handle.

Return type:

None

Module contents#

Client-side implementations of the Jupyter protocol