Adapters for Jupyter msg spec versions.
Bases: object
Base class for adapting messages
Override message_type(msg) methods to create adapters.
This will be called instead of the regular handler
on any reply with status != ok
Dict
[str
, Any
]
Dict
[str
, str
] = {}#
Update the header.
Dict
[str
, Any
]
Update the metadata.
Dict
[str
, Any
]
Update the message type.
Dict
[str
, Any
]
Bases: Adapter
Convert msg spec V4 to V5
Handle a complete reply.
Dict
[str
, Any
]
Handle a complete request.
Dict
[str
, Any
]
Handle display data.
Dict
[str
, Any
]
Handle an execute reply.
Dict
[str
, Any
]
Handle an execute request.
Dict
[str
, Any
]
Handle an input request.
Dict
[str
, Any
]
inspect_reply can’t be easily backward compatible
Dict
[str
, Any
]
Handle an inspect request.
Dict
[str
, Any
]
Handle a kernel info reply.
Dict
[str
, Any
]
Dict
[str
, str
] = {'object_info_reply': 'inspect_reply', 'object_info_request': 'inspect_request', 'pyerr': 'error', 'pyin': 'execute_input', 'pyout': 'execute_result'}#
Handle a stream message.
Dict
[str
, Any
]
Update the header.
Dict
[str
, Any
]
Bases: Adapter
Adapt msg protocol v5 to v4
Handle a complete reply.
Dict
[str
, Any
]
Handle a complete request.
Dict
[str
, Any
]
Handle a display data message.
Dict
[str
, Any
]
Handle an execute reply.
Dict
[str
, Any
]
Handle an execute request.
Dict
[str
, Any
]
Handle an input request.
Dict
[str
, Any
]
Handle a kernel info reply.
Dict
[str
, Any
]
Dict
[str
, str
] = {'error': 'pyerr', 'execute_input': 'pyin', 'execute_result': 'pyout', 'inspect_reply': 'object_info_reply', 'inspect_request': 'object_info_request'}#
inspect_reply can’t be easily backward compatible
Dict
[str
, Any
]
Handle an object info request.
Dict
[str
, Any
]
Handle a stream message.
Dict
[str
, Any
]
Update the header.
Dict
[str
, Any
]
Adapt a single message to a target version
msg (dict) – A Jupyter message.
to_version (int, optional) – The target major version. If unspecified, adapt to the current version.
Dict
[str
, Any
]
msg (dict) – A Jupyter message appropriate in the new version.
Turn a multiline code block and cursor position into a single line and new cursor position.
For adapting complete_
and object_info_request
.
Tuple
[str
, int
]
Reimplement token-finding logic from IPython 2.x javascript
for adapting object_info_request from v5 to v4
str
Base classes to manage a Client’s interaction with a running kernel
Bases: ZMQSocketChannel
A ZMQ socket in an async API
Gets a message if there is one that is ready.
Dict
[str
, Any
]
Get all messages that are currently ready.
List
[Dict
[str
, Any
]]
Is there a message that has been received?
bool
Socket
#
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.
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.
None
Close the heartbeat thread.
None
Is the heartbeat running and responsive (and not paused).
bool
Pause the heartbeat.
None
Run the heartbeat thread.
None
Stop the channel’s event loop and join its thread.
None
float
= 1.0#
Unpause the heartbeat.
None
Bases: Exception
An exception raised for an invalid port number.
Bases: object
A ZMQ socket wrapper
Close the socket channel.
None
Gets a message if there is one that is ready.
Dict
[str
, Any
]
Get all messages that are currently ready.
List
[Dict
[str
, Any
]]
Test whether the channel is alive.
bool
Is there a message that has been received?
bool
Pass a message to the ZMQ socket to send
None
Start the socket channel.
None
Close the socket channel.
None
Abstract base classes for kernel client channels
Bases: object
A base class for all channel ABCs.
Test whether the channel is alive.
bool
Start the channel.
None
Stop the channel.
None
Bases: ChannelABC
HBChannel ABC.
The docstrings for this class can be found in the base implementation:
jupyter_client.channels.HBChannel
Test whether the channel is beating.
bool
Pause the heartbeat channel.
None
Unpause the heartbeat channel.
None
Base class to manage the interaction with a running kernel
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.
bool
= True#
Are any of the channels created and running?
Request comm info
The msg_id of the message sent
Tab complete text in the kernel’s namespace.
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)
The msg_id of the message sent.
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
Get the control channel object for this kernel.
A trait whose value must be a subclass of a specified class.
Execute code in the kernel.
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.
The msg_id of the message sent.
Get the hb channel object for this kernel.
A trait whose value must be a subclass of a specified class.
Get entries from the kernel’s history list.
raw (bool) – If True, return the raw input.
output (bool) – If True, then return the output as well.
hist_access_type (str) –
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.
The ID of the message sent.
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.
The ID of the message sent.
Get metadata information about an object in the kernel’s namespace.
It is up to the kernel to determine the appropriate object to inspect.
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)
The msg_id of the message sent.
Get the iopub channel object for this kernel.
A trait whose value must be a subclass of a specified class.
Ask the kernel whether some code is complete and ready to execute.
The ID of the message sent.
Request kernel info
The msg_id of the message sent
Get the shell channel object for this kernel.
A trait whose value must be a subclass of a specified class.
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.
The msg_id of the message sent
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.
None
Get the stdin channel object for this kernel.
A trait whose value must be a subclass of a specified class.
Stops all the running channels for this kernel.
This stops their event loops and joins their threads.
None
Callable
Validate that the input is a dict with string keys and values.
Raises ValueError if not.
None
Abstract base class for kernel clients
Bases: object
KernelManager ABC.
The docstrings for this class can be found in the base implementation:
jupyter_client.client.KernelClient
Get whether the channels are running.
Start the channels for the client.
None
Stop the channels for the client.
None
Utilities for connecting to jupyter kernels
The ConnectionFileMixin
class in this module encapsulates the logic related to writing and reading connections files.
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
int
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.
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.
str
The absolute path of the connection file.
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.
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.
tuple
[Any
, ...
]
(shell, iopub, stdin, hb, control) (ints) – The five ports on localhost that have been forwarded to the kernel.
Generates a JSON config file, including the selection of random ports.
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.
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
Bases: JupyterConsoleApp
An app to manage an ipython console.
Bases: ConnectionFileMixin
The base Jupyter console application.
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 argv to be passed to kernel subprocess
Override in subclasses if any args should be passed to the kernel
None
Set to display confirmation dialog on exit. You can always use ‘exit’ or ‘quit’, to force a direct exit without any confirmation.
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 '#
Connect to an already running kernel
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
.
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.
None
Initialize the kernel client.
None
Initialize the kernel manager.
None
set up ssh tunnels, if needed.
None
None
JupyterConsoleApp.initialize(self,argv)
An instance of a Python list.
alias of BlockingKernelClient
The kernel manager class to use.
The name of the default kernel to start.
Union
[str
, Unicode
] = 'jupyter-console-mixin'#
Path to the ssh key to use for logging in to the ssh server.
The SSH server to use to connect to the kernel.
Utilities to manipulate JSON objects.
DEPRECATED: Use jupyter_client.jsonutil.json_default
Any
extract ISO8601 dates from unpacked JSON
Any
Any
default function for packing objects in JSON.
Any
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.
Union
[str
, datetime
, None
]
squash datetime objects into ISO8601 strings
Any
An application to launch a kernel by name in a local subprocess.
Bases: JupyterApp
Launch a kernel by name in a local subprocess.
Initialize the application.
None
The name of a kernel type to start
Log the connection info for the kernel.
None
Shutdown on SIGTERM or SIGINT (Ctrl-C)
None
Shut down the application.
None
Start the application.
None
Tools for managing kernel specs
Bases: HasTraits
A kernel spec model object.
An instance of a Python list.
A trait for unicode strings.
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
.
Create a KernelSpec object by reading kernel.json
Pass the path to the directory containing kernel.json.
An enum of strings where the case should be ignored.
A trait for unicode strings.
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
.
A trait for unicode strings.
A trait for unicode strings.
A trait for unicode strings.
Convert the kernel spec to a dict.
dict
[str
, Any
]
Serialise this kernelspec to a JSON object.
Returns a string.
str
Bases: LoggingConfigurable
A manager for kernel specs.
List of allowed kernel names.
By default, all installed kernels are allowed.
A trait for unicode strings.
If there is no Python kernelspec registered and the IPython kernel is available, ensure it is added to the spec list.
Returns a dict mapping kernel names to resource directories.
dict
[str
, str
]
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": ...} }, ... }
dict
[str
, Any
]
Returns a KernelSpec
instance for the given kernel_name.
Raises NoSuchKernel
if the given kernel name is not found.
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.
str
DEPRECATED: Use ipykernel.kernelspec.install
None
List of kernel directories to search. Later ones take priority over earlier.
The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior.
Remove a kernel spec directory by name.
Returns the path that was deleted.
str
A trait for unicode strings.
Deprecated, use KernelSpecManager.allowed_kernelspecs
Bases: KeyError
An error raised when there is no kernel of a give name.
Returns a dict mapping kernel names to resource directories.
dict
[str
, str
]
Returns a KernelSpec
instance for the given kernel_name.
Raises KeyError if the given kernel name is not found.
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.
str
DEPRECATED: Use ipykernel.kernelspec.install
None
Apps for managing kernel specs.
Bases: JupyterApp
An app to install a kernel spec.
Install the kernel spec with this name
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 the command line args.
None
Specify a prefix to install to, e.g. an env. The kernelspec will be installed in PREFIX/share/jupyter/kernels/
Replace any existing kernel spec with this name.
A trait for unicode strings.
Start the application.
None
Try to install the kernel spec to the per-user directory instead of the system or environment directory.
Bases: JupyterApp
An app to install the native kernel spec.
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 the application.
None
Try to install the kernel spec to the per-user directory instead of the system or environment directory.
Bases: Application
An app to manage kernel specs.
Start the application.
None
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
.
Bases: JupyterApp
An app to list kernel specs.
output spec name and location as machine-readable json.
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 the application.
dict
[str
, Any
] | None
Bases: JupyterApp
An app to list provisioners.
Start the application.
None
Bases: JupyterApp
An app to remove a kernel spec.
Force removal, don’t prompt for confirmation.
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 the command line args.
None
An instance of a Python list.
Start the application.
None
Utilities for launching kernels
Launches a localhost kernel, binding to the specified ports.
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
Popen
Popen instance for the kernel subprocess
Utilities for identifying local IP addresses.
Bases: Exception
Any
Any
Any
Any
Any
Base class to manage a running kernel
Bases: KernelManager
An async kernel manager.
Clean up resources when the kernel is shut down
None
Get a client for the manager.
DottedObjectName
#
A string holding a valid dotted object name in Python, such as A.b3._c
Type
#
A trait whose value must be a subclass of a specified class.
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
Wait for kernel shutdown, then kill process if it doesn’t shutdown.
This does not send shutdown requests - use request_shutdown()
first.
None
Interrupts the kernel by sending it a signal.
Unlike signal_kernel
, this operation is well supported on all platforms.
None
Is the kernel process still running?
bool
Performs any post startup tasks relative to the kernel.
**kw (optional) – keyword arguments that were used in the kernel process’s launch.
None
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.
**kw (optional) – keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs).
Tuple
[List
[str
], Dict
[str
, Any
]]
Send a shutdown request via control channel
None
Restarts a kernel with the arguments that were used to launch it.
now (bool, optional) –
If True, the kernel is forcefully restarted immediately, without having a chance to do any cleanup action. Otherwise the kernel is given 1s to clean up before a forceful restart is issued.
In all cases the kernel is restarted, the only difference is whether it is given a chance to perform a clean shutdown or not.
newports (bool, optional) – If the old kernel was launched with random ports, this flag decides whether the same ports and connection file will be used again. If False, the same ports and connection file are used. This is the default. If True, new random port numbers are chosen and a new connection file is written. It is still possible that the newly chosen random port numbers happen to be the same as the old ones.
**kw (optional) – Any options specified here will overwrite those used to launch the kernel.
None
Attempts to stop the kernel process cleanly.
This attempts to shutdown the kernels cleanly by:
Sending it a shutdown message over the control channel.
If that fails, the kernel is shutdown forcibly by sending it a signal.
now (bool) – Should the kernel be forcible killed now. This skips the first, nice shutdown attempt.
restart (bool) – Will this kernel be restarted after it is shutdown. When this is True, connection files will not be cleaned up.
None
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.
None
Starts a kernel on this host in a separate process.
If random ports (port=0) are being used, this method must be called before the channels are created.
**kw (optional) – keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs).
None
Bases: ConnectionFileMixin
Manages a single kernel in a subprocess on this host.
This version starts kernels with Popen.
Register a callback to be called when a kernel is restarted
None
Bool
#
Should we autorestart the kernel if it dies.
Bool
#
True if the MultiKernelManager should cache ports for this KernelManager instance
Clean up resources when the kernel is shut down
Any
Create a client configured to connect to our kernel
DottedObjectName
#
A string holding a valid dotted object name in Python, such as A.b3._c
Type
#
A trait whose value must be a subclass of a specified class.
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
Wait for kernel shutdown, then kill process if it doesn’t shutdown.
This does not send shutdown requests - use request_shutdown()
first.
Any
Replace templated args (e.g. {connection_file})
List
[str
]
Has a kernel process been started that we are actively managing.
Interrupts the kernel by sending it a signal.
Unlike signal_kernel
, this operation is well supported on all platforms.
Any
Is the kernel process still running?
Any
Union
[str
, Unicode
]#
A trait for unicode strings.
Union
[str
, Unicode
]#
A trait for unicode strings.
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
Performs any post startup tasks relative to the kernel.
**kw (optional) – keyword arguments that were used in the kernel process’s launch.
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.
**kw (optional) – keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs).
Any
Optional
[KernelProvisionerBase
] = None#
A future that resolves when the kernel process has started for the first time
Unregister a callback to be called when a kernel is restarted
None
Send a shutdown request via control channel
Any
Restarts a kernel with the arguments that were used to launch it.
now (bool, optional) –
If True, the kernel is forcefully restarted immediately, without having a chance to do any cleanup action. Otherwise the kernel is given 1s to clean up before a forceful restart is issued.
In all cases the kernel is restarted, the only difference is whether it is given a chance to perform a clean shutdown or not.
newports (bool, optional) – If the old kernel was launched with random ports, this flag decides whether the same ports and connection file will be used again. If False, the same ports and connection file are used. This is the default. If True, new random port numbers are chosen and a new connection file is written. It is still possible that the newly chosen random port numbers happen to be the same as the old ones.
**kw (optional) – Any options specified here will overwrite those used to launch the kernel.
Any
Attempts to stop the kernel process cleanly.
This attempts to shutdown the kernels cleanly by:
Sending it a shutdown message over the control channel.
If that fails, the kernel is shutdown forcibly by sending it a signal.
now (bool) – Should the kernel be forcible killed now. This skips the first, nice shutdown attempt.
restart (bool) – Will this kernel be restarted after it is shutdown. When this is True, connection files will not be cleaned up.
Any
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.
bool
= False#
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.
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.
**kw (optional) – keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs).
Any
Start the kernel restarter.
None
Stop the kernel restarter.
None
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
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.
TypeVar
(F
, bound= Callable
[...
, Any
])
Context manager to create a kernel in a subprocess.
The kernel is shut down when the context exits.
kernel_client
connected KernelClient instance
Start a new kernel, and return its Manager and Client
Tuple
[AsyncKernelManager
, AsyncKernelClient
]
Start a new kernel, and return its Manager and Client
Tuple
[KernelManager
, BlockingKernelClient
]
Abstract base class for kernel managers.
Bases: object
KernelManager ABC.
The docstrings for this class can be found in the base implementation:
jupyter_client.manager.KernelManager
Interrupt the kernel.
None
Test whether the kernel is alive.
bool
Restart the kernel.
None
Shut down the kernel.
None
Send a signal to the kernel.
None
Start the kernel.
None
A kernel manager for multiple kernels
Bases: MultiKernelManager
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
The kernel manager class. This is configurable to allow subclassing of the AsyncKernelManager for customized behavior.
Restart a kernel by its uuid, keeping the same ports.
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.
None
Shutdown all kernels.
None
Shutdown a kernel by its kernel uuid.
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?
None
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.
str
Whether to make kernels available before the process has started. The kernel has a .ready future which can be awaited before connecting
Bases: Exception
Bases: LoggingConfigurable
A class for managing multiple kernels.
add a callback for the KernelRestarter
None
Clean up a kernel’s resources
None
Return a zmq Socket connected to the control channel.
kernel_id (uuid) – The id of the kernel
identity (bytes (optional)) – The zmq identity of the socket
stream
zmq Socket or ZMQStream
Return a zmq Socket connected to the hb channel.
kernel_id (uuid) – The id of the kernel
identity (bytes (optional)) – The zmq identity of the socket
stream
zmq Socket or ZMQStream
Return a zmq Socket connected to the iopub channel.
kernel_id (uuid) – The id of the kernel
identity (bytes (optional)) – The zmq identity of the socket
stream
zmq Socket or ZMQStream
Return a zmq Socket connected to the shell channel.
kernel_id (uuid) – The id of the kernel
identity (bytes (optional)) – The zmq identity of the socket
stream
zmq Socket or ZMQStream
Return a zmq Socket connected to the stdin channel.
kernel_id (uuid) – The id of the kernel
identity (bytes (optional)) – The zmq identity of the socket
stream
zmq Socket or ZMQStream
A trait for unicode strings.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
The name of the default kernel to start
A trait for unicode strings.
Wait for a kernel to finish shutting down, and kill it if it doesn’t
None
Return a dictionary of connection data for a kernel.
kernel_id (uuid) – The id of the kernel.
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).
dict
Get the single KernelManager object for a kernel by its uuid.
kernel_id (uuid) – The id of the kernel.
Interrupt (SIGINT) the kernel by its uuid.
kernel_id (uuid) – The id of the kernel to interrupt.
None
Is the kernel alive.
This calls KernelManager.is_alive() which calls Popen.poll on the actual kernel subprocess.
kernel_id (uuid) – The id of the kernel.
bool
The kernel manager class. This is configurable to allow subclassing of the KernelManager for customized behavior.
this is kernel_manager_class after import
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
Return a list of the kernel ids of the active kernels.
list
[str
]
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
tuple
[KernelManager
, str
, str
]
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.
remove a callback for the KernelRestarter
None
Ask a kernel to shut down by its kernel uuid
None
Restart a kernel by its uuid, keeping the same ports.
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.
Any
Share a single zmq.Context to talk to all my kernels
Shutdown all kernels.
Any
Shutdown a kernel by its kernel uuid.
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?
Any
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.
kernel_id (uuid) – The id of the kernel to signal.
signum (int) – Signal number to send kernel.
None
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.
Any
Allow to update the environment of the given kernel.
Forward the update env request to the corresponding kernel. :rtype: None
decorator for proxying MKM.method(kernel_id) to individual KMs by ID
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.
Bases: LoggingConfigurable
Monitor and autorestart a kernel.
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.
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
.
Whether to include every poll event in debugging output.
Has to be set explicitly, because there will be a lot of output.
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
None
Whether to choose new random ports when restarting before the kernel is alive.
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.
The number of consecutive autorestarts before the kernel is presumed dead.
The time in seconds to consider the kernel to have completed a stable start up.
Start the polling of the kernel.
None
Stop the kernel polling.
None
Kernel heartbeat interval in seconds.
A Jupyter console app to run files.
Bases: JupyterApp
, JupyterConsoleApp
An Jupyter Console app to run files.
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
.
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
.
A trait which allows any value.
A trait which allows any value.
Handle SIGINT.
None
Wait for a kernel to be ready, and store kernel info
None
Initialize the app.
None
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.
Parse the command line arguments.
None
Start the application.
None
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.
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).
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.
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.
An int trait.
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
A casting version of the byte string trait.
Threshold (in bytes) beyond which an object’s buffer should be extracted to avoid pickling.
Whether to check PID to protect against calls after fork.
This check can be disabled if fork-safety is handled elsewhere.
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
Added in version 5.1.
Threshold (in bytes) beyond which a buffer should be sent without copying.
Debug output in the Session
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.
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).
msg – The nested message dict with top-level keys [header, parent_header, content, buffers]. The buffers are returned as memoryviews.
dict
An instance of a Python set.
The maximum number of digests to remember.
The digest history will be culled when it exceeds this value.
A trait which allows any value.
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.
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
(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.
two lists
The maximum number of items for a container to be introspected for custom serialization. Containers larger than this are pickled outright.
execution key, for signing messages.
path to file containing execution key.
Metadata dictionary, which serves as the default top-level metadata dict for each message.
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.
dict
[str
, Any
]
Create a header for a message type.
dict
[str
, Any
]
A trait which allows any value.
The name of the packer for serializing messages. Should be one of ‘json’, ‘pickle’, or an import name for a custom callable serializer.
An int trait.
Receive and unpack a message.
socket (ZMQStream or Socket) – The socket or stream to use in receiving.
[idents] is a list of idents and msg is a nested message dict of same format as self.msg returns.
[idents], msg
Build and send a message via stream or socket.
The message format used by this function internally is as follows:
buffer1,buffer2,…]
The serialize/deserialize methods convert the nested message dict into this format.
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.
msg – The constructed message.
dict
Send a raw message via ident path.
This method is used to send a already serialized message.
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.
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.
msg (dict or Message) – The next message dict as returned by the self.msg method.
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.
list
The UUID identifying this session.
Sign a message with HMAC digest. If no auth, return b’’.
msg_list (list) – The [p_header,p_parent,p_content] part of the message list.
bytes
The digest scheme used to construct the message signatures. Must have the form ‘hmac-HASH’.
A trait which allows any value.
The name of the unpacker for unserializing messages. Only used with custom functions for packer.
DEPRECATED Use deserialize instead.
dict
[str
, Any
]
Username for the Session. Default is your system username.
Bases: LoggingConfigurable
The Base class for configurables that have a Session, Context, logger, and IOLoop.
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
A trait for unicode strings.
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
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
Convert a json object to a bytes.
bytes
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.
None
Convert a json bytes or string to an object.
Any
Given a message or header, return the header.
dict
[str
, Any
]
Convert a json object to a bytes.
bytes
Convert a json bytes or string to an object.
Any
Create a new message header
dict
[str
, Any
]
Generate a new random id.
Avoids problematic runtime import in stdlib uuid on Python 2.
str
id string (16 random bytes as hex-encoded text, chunks separated by ‘-‘)
Return new_id as ascii bytes
bytes
Pack an object using the pickle module.
bytes
coerce unicode back to bytestrings.
Any
Return timezone-aware UTC timestamp
datetime
Defines a KernelClient that provides thread-safe sockets with async callbacks on message replies.
Bases: Thread
Run a pyzmq ioloop in a thread to send and receive messages
Close the io loop thread.
None
Run my loop, ignoring EINTR events in the poller
None
Start the IOLoop thread
Don’t return until self.ioloop is defined, which is created in the thread
None
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.
None
Bases: KernelClient
A KernelClient that provides thread-safe sockets with async callbacks on message replies.
A trait whose value must be a subclass of a specified class.
A trait whose value must be a subclass of a specified class.
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
A trait whose value must be a subclass of a specified class.
Is the kernel process still running?
bool
A trait whose value must be a subclass of a specified class.
Start the channels on the client.
None
A trait whose value must be a subclass of a specified class.
Stop the channels on the client.
None
Bases: object
A ZMQ socket invoking a callback in the ioloop
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.
None
Close the channel.
None
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.
timeout (float, optional) – The maximum amount of time to spend flushing, in seconds. The default is one second.
None
Whether the channel is alive.
bool
Subclasses should override this with a method processing any pending GUI events.
None
Queue a message to be sent from the IOLoop’s thread.
msg (message to send)
threadsafe (This is)
loop's (as it uses IOLoop.add_callback to give the)
action. (thread control of the)
None
Start the channel.
None
Stop the channel.
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.
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.
Any
Sends an interrupt event using the specified handle.
None
Client-side implementations of the Jupyter protocol
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4