client - communicating with kernels

See also

Messaging in Jupyter
The Jupyter messaging specification
class jupyter_client.KernelClient(**kwargs)

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

There are four 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.

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=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)

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=True, iopub=True, stdin=True, hb=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.

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.
Returns:

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)
Returns:

Return type:

The msg_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)
Returns:

Return type:

The msg_id of the message sent.

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.
Returns:

Return type:

The ID of the message sent.

comm_info(target_name=None)

Request comm info

Returns:
Return type:The msg_id of the message sent
is_complete(code)

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

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.

shutdown(restart=False)

Request an immediate kernel shutdown.

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.

Returns:
Return type:The msg_id of the message sent
get_shell_msg(*args, **kwargs)

Get a message from the shell channel

get_iopub_msg(*args, **kwargs)

Get a message from the iopub channel

get_stdin_msg(*args, **kwargs)

Get a message from the stdin channel

class jupyter_client.BlockingKernelClient(**kwargs)

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(code, silent=False, store_history=True, user_expressions=None, allow_stdin=None, stop_on_error=True, timeout=None, output_hook=None, stdin_hook=None)

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