client - communicating with kernels

See also

Messaging in Jupyter

The Jupyter messaging specification

class jupyter_client.KernelClient(**kwargs: Any)

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.

load_connection_file(connection_file: Optional[str] = None) None

Load connection info from JSON dict in self.connection_file.

Parameters

connection_file (unicode, optional) – Path to connection file to load. If unspecified, use self.connection_file

load_connection_info(info: Dict[str, Union[int, str, bytes]]) None

Load connection info from a dict containing connection info.

Typically this data comes from a connection file and is called by load_connection_file.

Parameters

info (dict) – Dictionary containing connection_info. See the connection_file spec for details.

start_channels(shell: bool = True, iopub: bool = True, stdin: bool = True, hb: bool = True, control: bool = True) None

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.

execute(code: str, silent: bool = False, store_history: bool = True, user_expressions: Optional[Dict[str, Any]] = None, allow_stdin: Optional[bool] = None, stop_on_error: bool = True) str

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.

complete(code: str, cursor_pos: Optional[int] = None) str

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.

inspect(code: str, cursor_pos: Optional[int] = None, detail_level: int = 0) str

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.

history(raw: bool = True, output: bool = False, hist_access_type: str = 'range', **kwargs: Any) str

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.

comm_info(target_name: Optional[str] = None) str

Request comm info

Return type

The msg_id of the message sent

is_complete(code: str) str

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

input(string: str) None

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.

shutdown(restart: bool = False) str

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

class jupyter_client.BlockingKernelClient(**kwargs: Any)

A KernelClient with blocking APIs

get_[channel]_msg() methods wait for and return messages on channels, raising queue.Empty if no message arrives within timeout seconds.

execute_interactive(**kwargs)

Execute code in the kernel interactively

Output will be redisplayed, and stdin prompts will be relayed as well. If an IPython kernel is detected, rich output will be displayed.

You can pass a custom output_hook callable that will be called with every IOPub message that is produced instead of the default redisplay.

New in version 5.0.

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.

  • timeout (float or None (default: None)) – Timeout to use when waiting for a reply

  • output_hook (callable(msg)) – Function to be called with output messages. If not specified, output will be redisplayed.

  • stdin_hook (callable(msg)) – Function or awaitable to be called with stdin_request messages. If not specified, input/getpass will be called.

Returns

reply – The reply message for this request

Return type

dict

get_shell_msg(**kwargs)

Get a message from the shell channel

get_iopub_msg(**kwargs)

Get a message from the iopub channel

get_stdin_msg(**kwargs)

Get a message from the stdin channel

get_control_msg(**kwargs)

Get a message from the control channel

wait_for_ready(**kwargs)

Waits for a response when a client is blocked

  • Sets future time for timeout

  • Blocks on shell channel until a message is received

  • Exit if the kernel has died

  • If client times out before receiving a message from the kernel, send RuntimeError

  • Flush the IOPub channel

is_alive(**kwargs)

Is the kernel process still running?

class jupyter_client.AsyncKernelClient(**kwargs: Any)

A KernelClient with async APIs

get_[channel]_msg() methods wait for and return messages on channels, raising queue.Empty if no message arrives within timeout seconds.

AsyncKernelClient is identical to BlockingKernelClient but the methods described above are async.