ipykernel package#

Subpackages#

Submodules#

Compiler helpers for the debugger.

class ipykernel.compiler.XCachingCompiler(*args, **kwargs)#

Bases: CachingCompiler

A custom caching compiler.

get_code_name(raw_code, code, number)#

Get the code name.

ipykernel.compiler.convert_to_long_pathname(filename)#
ipykernel.compiler.get_file_name(code)#

Get a file name.

ipykernel.compiler.get_tmp_directory()#

Get a temp directory.

ipykernel.compiler.get_tmp_hash_seed()#

Get a temp hash seed.

ipykernel.compiler.murmur2_x86(data, seed)#

Get the murmur2 hash.

Connection file-related utilities for the kernel

ipykernel.connect.connect_qtconsole(connection_file=None, argv=None)#

Connect a qtconsole to the current kernel.

This is useful for connecting a second qtconsole to a kernel, or to a local notebook.

Return type:

Popen[Any]

Parameters#

connection_filestr [optional]

The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython,

If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel.

argvlist [optional]

Any extra args to be passed to the console.

Returns#

subprocess.Popen instance running the qtconsole frontend

ipykernel.connect.get_connection_file(app=None)#

Return the path to the connection file of an app

Return type:

str

Parameters#

appIPKernelApp instance [optional]

If unspecified, the currently running app will be used

ipykernel.connect.get_connection_info(connection_file=None, unpack=False)#

Return the connection information for the current Kernel.

Return type:

str | dict[str, Any]

Parameters#

connection_filestr [optional]

The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython,

If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel.

unpackbool [default: False]

if True, return the unpacked dict, otherwise just the string contents of the file.

Returns#

The connection dictionary of the current kernel, as string or dict, depending on unpack.

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

Return type:

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

Parameters#

fnameunicode

The path to the file to write

shell_portint, optional

The port to use for ROUTER (shell) channel.

iopub_portint, optional

The port to use for the SUB channel.

stdin_portint, optional

The port to use for the ROUTER (raw input) channel.

control_portint, optional

The port to use for the ROUTER (control) channel.

hb_portint, optional

The port to use for the heartbeat REP channel.

ipstr, optional

The ip address the kernel will bind to.

keystr, optional

The Session key used for message authentication.

signature_schemestr, 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_namestr, optional

The name of the kernel currently connected to.

A thread for a control channel.

class ipykernel.control.ControlThread(**kwargs)#

Bases: Thread

A thread for a control channel.

run()#

Run the thread.

stop()#

Stop the thread.

This method is threadsafe.

Debugger implementation for the IPython kernel.

class ipykernel.debugger.Debugger(log, debugpy_stream, event_callback, shell_socket, session, just_my_code=True)#

Bases: object

The debugger class.

accept_variable(variable_name)#

Accept a variable by name.

async attach(message)#

Handle an attach message.

async configurationDone(message)#

Handle a configuration done message.

async copyToGlobals(message)#
async debugInfo(message)#

Handle a debug info message.

async dumpCell(message)#

Handle a dump cell message.

async handle_stopped_event()#

Handle a stopped event.

async inspectVariables(message)#

Handle an inspect variables message.

async modules(message)#

Handle a modules message.

async process_request(message)#

Process a request.

async richInspectVariables(message)#

Handle a rich inspect variables message.

async setBreakpoints(message)#

Handle a set breakpoints message.

async source(message)#

Handle a source message.

async stackTrace(message)#

Handle a stack trace message.

start()#

Start the debugger.

started_debug_msg_types = ['dumpCell', 'setBreakpoints', 'source', 'stackTrace', 'variables', 'attach', 'configurationDone']#
static_debug_msg_types = ['debugInfo', 'inspectVariables', 'richInspectVariables', 'modules', 'copyToGlobals']#
stop()#

Stop the debugger.

property tcp_client#
async variables(message)#

Handle a variables message.

class ipykernel.debugger.DebugpyClient(log, debugpy_stream, event_callback)#

Bases: object

A client for debugpy.

connect_tcp_socket()#

Connect to the tcp socket.

disconnect_tcp_socket()#

Disconnect from the tcp socket.

get_host_port()#

Get the host debugpy port.

receive_dap_frame(frame)#

Receive a dap frame.

async send_dap_request(msg)#

Send a dap request.

class ipykernel.debugger.DebugpyMessageQueue(event_callback, log)#

Bases: object

A debugpy message queue.

HEADER = 'Content-Length: '#
HEADER_LENGTH = 16#
SEPARATOR = '\r\n\r\n'#
SEPARATOR_LENGTH = 4#
async get_message()#

Get a message from the queue.

put_tcp_frame(frame)#

Put a tcp frame in the queue.

class ipykernel.debugger.VariableExplorer#

Bases: object

A variable explorer.

get_children_variables(variable_ref=None)#

Get the child variables for a variable reference.

track()#

Start tracking.

untrack_all()#

Stop tracking.

Replacements for sys.displayhook that publish over ZMQ.

class ipykernel.displayhook.ZMQDisplayHook(session, pub_socket)#

Bases: object

A simple displayhook that publishes the object’s repr over a ZeroMQ socket.

get_execution_count()#

This method is replaced in kernelapp

set_parent(parent)#

Set the parent header.

topic = b'execute_result'#
class ipykernel.displayhook.ZMQShellDisplayHook(**kwargs: Any)#

Bases: DisplayHook

A displayhook subclass that publishes data using ZeroMQ. This is intended to work with an InteractiveShell instance. It sends a dict of different representations of the object.

finish_displayhook()#

Finish up all displayhook activities.

msg: dict[str, t.Any] | None#
parent_header#

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.

pub_socket#

A trait which allows any value.

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

set_parent(parent)#

Set the parent for outbound messages.

start_displayhook()#

Start the display hook.

topic = None#
write_format_data(format_dict, md_dict=None)#

Write format data to the message.

write_output_prompt()#

Write the output prompt.

Simple function for embedding an IPython kernel

ipykernel.embed.embed_kernel(module=None, local_ns=None, **kwargs)#

Embed and start an IPython kernel in a given scope.

Parameters#

moduleModuleType, optional

The module to load into IPython globals (default: caller)

local_nsdict, optional

The namespace to load into IPython user namespace (default: caller)

kwargsdict, optional

Further keyword args are relayed to the IPKernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process.

Event loop integration for the ZeroMQ-based kernels.

ipykernel.eventloops.enable_gui(gui, kernel=None)#

Enable integration with a given GUI

ipykernel.eventloops.loop_asyncio(kernel)#

Start a kernel with asyncio event loop support.

ipykernel.eventloops.loop_asyncio_exit(kernel)#

Exit hook for asyncio

ipykernel.eventloops.loop_cocoa(kernel)#

Start the kernel, coordinating with the Cocoa CFRunLoop event loop via the matplotlib MacOSX backend.

ipykernel.eventloops.loop_cocoa_exit(kernel)#

Exit the cocoa loop.

ipykernel.eventloops.loop_gtk(kernel)#

Start the kernel, coordinating with the GTK event loop

ipykernel.eventloops.loop_gtk3(kernel)#

Start the kernel, coordinating with the GTK event loop

ipykernel.eventloops.loop_gtk3_exit(kernel)#

Exit the gtk3 loop.

ipykernel.eventloops.loop_gtk_exit(kernel)#

Exit the gtk loop.

ipykernel.eventloops.loop_qt(kernel)#

Event loop for all supported versions of Qt.

ipykernel.eventloops.loop_qt5(kernel)#

Event loop for all supported versions of Qt.

ipykernel.eventloops.loop_qt_exit(kernel)#
ipykernel.eventloops.loop_tk(kernel)#

Start a kernel with the Tk event loop.

ipykernel.eventloops.loop_tk_exit(kernel)#

Exit the tk loop.

ipykernel.eventloops.loop_wx(kernel)#

Start a kernel with wx event loop support.

ipykernel.eventloops.loop_wx_exit(kernel)#

Exit the wx loop.

ipykernel.eventloops.make_qt_app_for_kernel(gui, kernel)#

Sets the QT_API environment variable if it isn’t already set.

ipykernel.eventloops.register_integration(*toolkitnames)#

Decorator to register an event loop to integrate with the IPython kernel

The decorator takes names to register the event loop as for the %gui magic. You can provide alternative names for the same toolkit.

The decorated function should take a single argument, the IPython kernel instance, arrange for the event loop to call kernel.do_one_iteration() at least every kernel._poll_interval seconds, and start the event loop.

ipykernel.eventloops provides and registers such functions for a few common event loops.

ipykernel.eventloops.set_qt_api_env_from_gui(gui)#

Sets the QT_API environment variable by trying to import PyQtx or PySidex.

The user can generically request qt or a specific Qt version, e.g. qt6. For a generic Qt request, we let the mechanism in IPython choose the best available version by leaving the QT_API environment variable blank.

For specific versions, we check to see whether the PyQt or PySide implementations are present and set QT_API accordingly to indicate to IPython which version we want. If neither implementation is present, we leave the environment variable set so IPython will generate a helpful error message.

Notes#

  • If the environment variable is already set, it will be used unchanged, regardless of what the user requested.

The client and server for a basic ping-pong style heartbeat.

class ipykernel.heartbeat.Heartbeat(context, addr=None)#

Bases: Thread

A simple ping-pong style heartbeat that runs in a thread.

pick_port()#

Pick a port for the heartbeat.

run()#

Run the heartbeat thread.

Wrappers for forwarding stdout/stderr over zmq

class ipykernel.iostream.BackgroundSocket(io_thread)#

Bases: object

Wrapper around IOPub thread that provides zmq send[_multipart]

io_thread = None#
send(msg, *args, **kwargs)#

Send a message to the socket.

send_multipart(*args, **kwargs)#

Schedule send in IO thread

class ipykernel.iostream.IOPubThread(socket, pipe=False)#

Bases: object

An object for sending IOPub messages in a background thread

Prevents a blocking main thread from delaying output from threads.

IOPubThread(pub_socket).background_socket is a Socket-API-providing object whose IO is always run in a thread.

close()#

Close the IOPub thread.

property closed#
schedule(f)#

Schedule a function to be called in our IO thread.

If the thread is not running, call immediately.

send_multipart(*args, **kwargs)#

send_multipart schedules actual zmq send in my thread.

If my thread isn’t running (e.g. forked process), send immediately.

start()#

Start the IOPub thread

stop()#

Stop the IOPub thread

class ipykernel.iostream.OutStream(session, pub_thread, name, pipe=None, echo=None, *, watchfd=True, isatty=False)#

Bases: TextIOBase

A file like object that publishes the stream to a 0MQ PUB socket.

Output is handed off to an IO Thread

close()#

Close the stream.

property closed#
encoding = 'UTF-8'#
fileno()#

Things like subprocess will peak and write to the fileno() of stderr/stdout.

flush()#

trigger actual zmq send

send will happen in the background thread

flush_interval = 0.2#
flush_timeout = 10#
isatty()#

Return a bool indicating whether this is an ‘interactive’ stream.

Returns:

Boolean

property parent_header#
register_hook(hook)#

Registers a hook with the thread-local storage.

Parameters#

hook : Any callable object

Returns#

Either a publishable message, or None. The hook callable must return a message from the __call__ method if they still require the session.send method to be called after transformation. Returning None will halt that execution path, and session.send will not be called.

set_parent(parent)#

Set the parent header.

topic = None#
unregister_hook(hook)#

Un-registers a hook with the thread-local storage.

Parameters#

hookAny callable object which has previously been

registered as a hook.

Returns#

bool - True if the hook was removed, False if it wasn’t

found.

writable()#

Test whether the stream is writable.

write(string)#

Write to current stream after encoding if necessary

Return type:

Optional[int]

Returns#

lenint

number of items from input parameter written to stream.

writelines(sequence)#

Write lines to the stream.

The IPython kernel implementation

class ipykernel.ipkernel.IPythonKernel(**kwargs: Any)#

Bases: Kernel

The IPython Kernel class.

property banner#
debugpy_stream#

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

dispatch_debugpy(msg)#
do_apply(content, bufs, msg_id, reply_metadata)#

Handle an apply request.

do_clear()#

Clear the kernel.

do_complete(code, cursor_pos)#

Handle code completion.

async do_debug_request(msg)#

Handle a debug request.

async do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_meta=None, cell_id=None)#

Handle code execution.

do_history(hist_access_type, output, raw, session=0, start=0, stop=None, n=None, pattern=None, unique=False)#

Handle code history.

do_inspect(code, cursor_pos, detail_level=0, omit_sections=())#

Handle code inspection.

do_is_complete(code)#

Handle an is_complete request.

do_shutdown(restart)#

Handle kernel shutdown.

async execute_request(stream, ident, parent)#

Override for cell output - cell reconciliation.

property execution_count#

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

finish_metadata(parent, metadata, reply_content)#

Finish populating metadata.

Run after completing an execution request.

An instance of a Python list.

implementation: str = 'ipython'#
implementation_version: str = '8.26.0'#
init_metadata(parent)#

Initialize metadata.

Run at the beginning of each execution request.

language_info: dict[str, object] = {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.11.9'}#
async poll_stopped_queue()#

Poll the stopped queue.

set_parent(ident, parent, channel='shell')#

Overridden from parent to tell the display hook and output streams about the parent message.

shell#

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

shell_class#

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

start()#

Start the kernel.

use_experimental_completions#

Set this flag to False to deactivate the use of experimental IPython completion APIs.

user_module#

A trait which allows any value.

user_ns#

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

class ipykernel.ipkernel.Kernel(**kwargs: Any)#

Bases: IPythonKernel

DEPRECATED. An alias for the IPython kernel class.

Utilities to manipulate JSON objects.

ipykernel.jsonutil.encode_images(format_dict)#

b64-encodes images in a displaypub format dict

Perhaps this should be handled in json_clean itself?

Parameters#

format_dictdict

A dictionary of display data keyed by mime-type

Returns#

format_dictdict

A copy of the same dictionary, but binary image data (‘image/png’, ‘image/jpeg’ or ‘application/pdf’) is base64-encoded.

ipykernel.jsonutil.json_clean(obj)#

Deprecated, this is a no-op for jupyter-client>=7.

Clean an object to ensure it’s safe to encode in JSON.

Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied.

Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string ‘1’ as keys) will cause a ValueError to be raised.

Parameters#

obj : any python object

Returns#

outobject

A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not encode its inputs, it simply sanitizes it so that there will be no encoding errors later.

An Application for launching a kernel

class ipykernel.kernelapp.IPKernelApp(**kwargs: Any)#

Bases: BaseIPythonApplication, InteractiveShellApp, ConnectionFileMixin

The IPYKernel application class.

property abs_connection_file#
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.

capture_fd_output#

Attempt to capture and forward low-level output, e.g. produced by Extension libraries.

classes: ClassesType = [<class 'ipykernel.ipkernel.IPythonKernel'>, <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, <class 'IPython.core.profiledir.ProfileDir'>, <class 'jupyter_client.session.Session'>]#
cleanup_connection_file()#

Clean up our connection file.

close()#

Close zmq sockets in an orderly fashion

configure_tornado_logger()#

Configure the tornado logging.Logger.

Must set up the tornado logger or else tornado will call basicConfig for the root logger which makes the root logger go to the real sys.stderr instead of the capture streams. This function mimics the setup of logging.basicConfig.

connection_dir#

A trait for unicode strings.

context: zmq.Context[t.Any] | None#

A trait which allows any value.

control_socket#

A trait which allows any value.

control_thread#

A trait which allows any value.

debug_shell_socket#

A trait which allows any value.

debugpy_socket#

A trait which allows any value.

displayhook_class#

The importstring for the DisplayHook factory

excepthook(etype, evalue, tb)#

Handle an exception.

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.

heartbeat#

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

init_blackhole()#

redirects stdout/stderr to devnull if necessary

init_connection_file()#

Initialize our connection file.

init_control(context)#

Initialize the control channel.

init_crash_handler()#

Initialize the crash handler.

init_gui_pylab()#

Enable GUI event loop integration, taking pylab into account.

init_heartbeat()#

start the heart beating

init_io()#

Redirect input streams and set a display hook.

init_iopub(context)#

Initialize the iopub channel.

init_kernel()#

Create the Kernel object itself

init_pdb()#

Replace pdb with IPython’s version that is interruptible.

With the non-interruptible version, stopping pdb() locks up the kernel in a non-recoverable state.

init_poller()#

Initialize the poller.

init_shell()#

Initialize the shell channel.

init_signal()#

Initialize the signal handler.

init_sockets()#

Create a context, a session, and the kernel sockets.

initialize(argv=None)#

Initialize the application.

interrupt#

ONLY USED ON WINDOWS Interrupt this process when the parent is signaled.

iopub_socket#

A trait which allows any value.

iopub_thread#

A trait which allows any value.

kernel#

A trait which allows any value.

kernel_class#

The Kernel subclass to be used.

This should allow easy reuse of the IPKernelApp entry point to configure and launch kernels other than IPython’s own.

log_connection_info()#

display connection info, and store ports

name: str | Unicode[str, str | bytes] = 'ipython-kernel'#
no_stderr#

redirect stderr to the null device

no_stdout#

redirect stdout to the null device

outstream_class#

The importstring for the OutStream factory

parent_handle#

kill this process if its parent dies. On Windows, the argument specifies the HANDLE of the parent process, otherwise it is simply boolean.

patch_io()#

Patch important libraries that can’t handle sys.stdout forwarding

poller#

A trait which allows any value.

quiet#

Only send stdout/stderr to output stream

reset_io()#

restore original io

restores state after init_io

shell_socket#

A trait which allows any value.

start()#

Start the application.

stdin_socket#

A trait which allows any value.

subcommands: dict[str, t.Any] | Dict[str, t.Any] = {'install': ('ipykernel.kernelspec.InstallIPythonKernelSpecApp', 'Install the IPython kernel')}#
trio_loop#

Set main event loop.

write_connection_file()#

write connection info to JSON file

ipykernel.kernelapp.main()#

Run an IPKernel as an application

Base class for a kernel that talks to frontends over 0MQ.

class ipykernel.kernelbase.Kernel(**kwargs: Any)#

Bases: SingletonConfigurable

The base kernel class.

async abort_request(stream, ident, parent)#

abort a specific msg by id

aborted#

An instance of a Python set.

async apply_request(stream, ident, parent)#

Handle an apply request.

banner: str#
async clear_request(stream, idents, parent)#

Clear our namespace.

async comm_info_request(stream, ident, parent)#

Handle a comm info request.

async complete_request(stream, ident, parent)#

Handle a completion request.

async connect_request(stream, ident, parent)#

Handle a connect request.

control_msg_types = ['execute_request', 'complete_request', 'inspect_request', 'history_request', 'comm_info_request', 'kernel_info_request', 'connect_request', 'shutdown_request', 'is_complete_request', 'interrupt_request', 'apply_request', 'clear_request', 'abort_request', 'debug_request', 'usage_request']#
control_stream#

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

control_thread#

A trait which allows any value.

debug_just_my_code#

Set to False if you want to debug python standard and dependent libraries.

async debug_request(stream, ident, parent)#

Handle a debug request.

debug_shell_socket#

A trait which allows any value.

dispatch_control(msg)#
async dispatch_queue()#

Coroutine to preserve order of message handling

Ensures that only one message is processing at a time, even when the handler is async

async dispatch_shell(msg)#

dispatch shell requests

do_apply(content, bufs, msg_id, reply_metadata)#

DEPRECATED

do_clear()#

DEPRECATED since 4.0.3

do_complete(code, cursor_pos)#

Override in subclasses to find completions.

async do_debug_request(msg)#
do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_meta=None, cell_id=None)#

Execute user code. Must be overridden by subclasses.

do_history(hist_access_type, output, raw, session=None, start=None, stop=None, n=None, pattern=None, unique=False)#

Override in subclasses to access history.

do_inspect(code, cursor_pos, detail_level=0, omit_sections=())#

Override in subclasses to allow introspection.

do_is_complete(code)#

Override in subclasses to find completions.

async do_one_iteration()#

Process a single shell message

Any pending control messages will be flushed as well

Changed in version 5: This is now a coroutine

do_shutdown(restart)#

Override in subclasses to do things when the frontend shuts down the kernel.

enter_eventloop()#

enter eventloop

eventloop#

A trait which allows any value.

async execute_request(stream, ident, parent)#

handle an execute_request

execution_count = 0#
finish_metadata(parent, metadata, reply_content)#

Finish populating metadata.

Run after completing an execution request.

get_parent(channel=None)#

Get the parent request associated with a channel.

Added in version 6.

Parameters#

channelstr

the name of the channel (‘shell’ or ‘control’)

Returns#

messagedict

the parent message for the most recent request on the channel.

get_process_metric_value(process, name, attribute=None)#

Get the process metric value.

getpass(prompt='', stream=None)#

Forward getpass to frontends

Raises#

StdinNotImplementedError if active frontend doesn’t support stdin.

An instance of a Python list.

async history_request(stream, ident, parent)#

Handle a history request.

ident#

A trait for unicode strings.

implementation: str#
implementation_version: str#
init_metadata(parent)#

Initialize metadata.

Run at the beginning of execution requests.

async inspect_request(stream, ident, parent)#

Handle an inspect request.

int_id#

An int trait.

async interrupt_request(stream, ident, parent)#

Handle an interrupt request.

iopub_socket#

A trait which allows any value.

iopub_thread#

A trait which allows any value.

async is_complete_request(stream, ident, parent)#

Handle an is_complete request.

property kernel_info#
async kernel_info_request(stream, ident, parent)#

Handle a kernel info request.

language_info: dict[str, object] = {}#
log: logging.Logger#

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

msg_types = ['execute_request', 'complete_request', 'inspect_request', 'history_request', 'comm_info_request', 'kernel_info_request', 'connect_request', 'shutdown_request', 'is_complete_request', 'interrupt_request', 'apply_request']#
async poll_control_queue()#
post_handler_hook()#

Hook to execute after calling message handler

pre_handler_hook()#

Hook to execute before calling message handler

async process_control(msg)#

dispatch control requests

async process_one(wait=True)#

Process one request

Returns None if no message was handled.

processes: dict[str, psutil.Process] = {}#
profile_dir#

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

raw_input(prompt='')#

Forward raw_input to frontends

Raises#

StdinNotImplementedError if active frontend doesn’t support stdin.

record_ports(ports)#

Record the ports that this kernel is using.

The creator of the Kernel instance must call this methods if they want the connect_request() method to return the port numbers.

schedule_dispatch(dispatch, *args)#

schedule a message for dispatch

send_response(stream, msg_or_type, content=None, ident=None, buffers=None, track=False, header=None, metadata=None, channel=None)#

Send a response to the message we’re currently processing.

This accepts all the parameters of jupyter_client.session.Session.send() except parent.

This relies on set_parent() having been called for the current message.

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

set_parent(ident, parent, channel='shell')#

Set the current parent request

Side effects (IOPub messages) and replies are associated with the request that caused them via the parent_header.

The parent identity is used to route input_request messages on the stdin channel.

shell_stream#

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

shell_streams: List[t.Any]#

Deprecated shell_streams alias. Use shell_stream

Changed in version 6.0: shell_streams is deprecated. Use shell_stream.

should_handle(stream, msg, idents)#

Check whether a shell-channel message should be handled

Allows subclasses to prevent handling of certain messages (e.g. aborted requests).

async shutdown_request(stream, ident, parent)#

Handle a shutdown request.

start()#

register dispatchers for streams

stdin_socket#

A trait which allows any value.

stop_on_error_timeout#

time (in seconds) to wait for messages to arrive when aborting queued requests after an error.

Requests that arrive within this window after an error will be cancelled.

Increase in the event of unusually slow network causing significant delays, which can manifest as e.g. “Run all” in a notebook aborting some, but not all, messages after an error.

async usage_request(stream, ident, parent)#

Handle a usage request.

The IPython kernel spec for Jupyter

class ipykernel.kernelspec.InstallIPythonKernelSpecApp(**kwargs)#

Bases: Application

Dummy app wrapping argparse

initialize(argv=None)#

Initialize the app.

Return type:

None

name: str | Unicode[str, str | bytes]#

A trait for unicode strings.

start()#

Start the app.

Return type:

None

ipykernel.kernelspec.get_kernel_dict(extra_arguments=None, python_arguments=None)#

Construct dict for kernel.json

Return type:

dict[str, Any]

ipykernel.kernelspec.install(kernel_spec_manager=None, user=False, kernel_name='python3', display_name=None, prefix=None, profile=None, env=None, frozen_modules=False)#

Install the IPython kernelspec for Jupyter

Return type:

str

Parameters#

kernel_spec_managerKernelSpecManager [optional]

A KernelSpecManager to use for installation. If none provided, a default instance will be created.

userbool [default: False]

Whether to do a user-only install, or system-wide.

kernel_namestr, optional

Specify a name for the kernelspec. This is needed for having multiple IPython kernels for different environments.

display_namestr, optional

Specify the display name for the kernelspec

profilestr, optional

Specify a custom profile to be loaded by the kernel.

prefixstr, optional

Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env.

envdict, optional

A dictionary of extra environment variables for the kernel. These will be added to the current environment variables before the kernel is started

frozen_modulesbool, optional

Whether to use frozen modules for potentially faster kernel startup. Using frozen modules prevents debugging inside of some built-in Python modules, such as io, abc, posixpath, ntpath, or stat. The frozen modules are used in CPython for faster interpreter startup. Ignored for cPython <3.11 and for other Python implementations.

Returns#

The path where the kernelspec was installed.

ipykernel.kernelspec.make_ipkernel_cmd(mod='ipykernel_launcher', executable=None, extra_arguments=None, python_arguments=None)#

Build Popen command list for launching an IPython kernel.

Return type:

list[str]

Parameters#

modstr, optional (default ‘ipykernel’)

A string of an IPython module whose __main__ starts an IPython kernel

executablestr, optional (default sys.executable)

The Python executable to use for the kernel process.

extra_argumentslist, optional

A list of extra arguments to pass when executing the launch code.

Returns#

A Popen command list

ipykernel.kernelspec.write_kernel_spec(path=None, overrides=None, extra_arguments=None, python_arguments=None)#

Write a kernel spec directory to path

If path is not specified, a temporary directory is created. If overrides is given, the kernelspec JSON is updated before writing.

The path to the kernelspec is always returned.

Return type:

str

A PUB log handler.

class ipykernel.log.EnginePUBHandler(engine, *args, **kwargs)#

Bases: PUBHandler

A simple PUBHandler subclass that sets root_topic

engine = None#
property root_topic#

this is a property, in case the handler is created before the engine gets registered with an id

A parent poller for unix.

class ipykernel.parentpoller.ParentPollerUnix#

Bases: Thread

A Unix-specific daemon thread that terminates the program immediately when the parent process no longer exists.

run()#

Run the poller.

class ipykernel.parentpoller.ParentPollerWindows(interrupt_handle=None, parent_handle=None)#

Bases: Thread

A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists.

run()#

Run the poll loop. This method never returns.

A trio loop runner.

class ipykernel.trio_runner.TrioRunner#

Bases: object

A trio loop runner.

initialize(kernel, io_loop)#

Initialize the runner.

interrupt(signum, frame)#

Interuppt the runner.

run()#

Run the loop.

A ZMQ-based subclass of InteractiveShell.

This code is meant to ease the refactoring of the base InteractiveShell into something with a cleaner architecture for 2-process use, without actually breaking InteractiveShell itself. So we’re doing something a bit ugly, where we subclass and override what we want to fix. Once this is working well, we can go back to the base class and refactor the code for a cleaner inheritance implementation that doesn’t rely on so much monkeypatching.

But this lets us maintain a fully working IPython as we develop the new machinery. This should thus be thought of as scaffolding.

class ipykernel.zmqshell.KernelMagics(**kwargs: Any)#

Bases: Magics

Kernel magics.

autosave(arg_s)#

Set the autosave interval in the notebook (in seconds).

The default value is 120, or two minutes. %autosave 0 will disable autosave.

This magic only has an effect when called from the notebook interface. It has no effect when called in a startup file.

clear(arg_s)#

Clear the terminal.

connect_info(arg_s)#

Print information for connecting other clients to this kernel

It will print the contents of this session’s connection file, as well as shortcuts for local clients.

In the simplest case, when called from the most recently launched kernel, secondary clients can be connected, simply with:

$> jupyter <app> –existing

edit(parameter_s='', last_call=None)#

Bring up an editor and execute the resulting code.

Usage:

%edit [options] [args]

%edit runs an external text editor. You will need to set the command for this editor via the TerminalInteractiveShell.editor option in your configuration file before it will work.

This command allows you to conveniently edit multi-line code right in your IPython session.

If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don’t forget to save it!).

Options:

-n <number>

Open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax ‘editor +N filename’, but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax.

-p

Call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was.

-r

Use ‘raw’ input. This option only applies to input taken from the user’s history. By default, the ‘processed’ history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython’s own processor.

Arguments:

If arguments are given, the following possibilities exist:

  • The arguments are numbers or pairs of colon-separated numbers (like 1 4:8 9). These are interpreted as lines of previous input to be loaded into the editor. The syntax is the same of the %macro command.

  • If the argument doesn’t start with a number, it is evaluated as a variable and its contents loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits).

  • If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use %edit function to load an editor exactly at the point where ‘function’ is defined, edit it and have the file be executed automatically.

    If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro’s data. Upon exit, the macro is reloaded with the contents of the file.

    Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the ‘+NUMBER’ parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do.

  • If the argument is not found as a variable, IPython will look for a file with that name (adding .py if necessary) and load it into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace.

Unlike in the terminal, this is designed to use a GUI editor, and we do not know when it has closed. So the file you edit will not be automatically executed or printed.

Note that %edit is also available through the alias %ed.

less(arg_s)#

Show a file through the pager.

Files ending in .py are syntax-highlighted.

magics = {'cell': {}, 'line': {'autosave': 'autosave', 'clear': 'clear', 'connect_info': 'connect_info', 'edit': 'edit', 'less': 'less', 'man': 'man', 'more': 'less', 'qtconsole': 'qtconsole'}}#
man(arg_s)#

Find the man page for the given command and display in pager.

more(arg_s)#

Show a file through the pager.

Files ending in .py are syntax-highlighted.

qtconsole(arg_s)#

Open a qtconsole connected to this kernel.

Useful for connecting a qtconsole to running notebooks, for better debugging.

registered = True#
class ipykernel.zmqshell.ZMQDisplayPublisher(**kwargs: Any)#

Bases: DisplayPublisher

A display publisher that publishes data using a ZeroMQ PUB socket.

clear_output(wait=False)#

Clear output associated with the current execution (cell).

Parameters#

waitbool (default: False)

If True, the output will not be cleared immediately, instead waiting for the next display before clearing. This reduces bounce during repeated clear & display loops.

parent_header#

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.

pub_socket#

A trait which allows any value.

publish(data, metadata=None, transient=None, update=False)#

Publish a display-data message

Parameters#

datadict

A mime-bundle dict, keyed by mime-type.

metadatadict, optional

Metadata associated with the data.

transientdict, optional, keyword-only

Transient data that may only be relevant during a live display, such as display_id. Transient data should not be persisted to documents.

updatebool, optional, keyword-only

If True, send an update_display_data message instead of display_data.

register_hook(hook)#

Registers a hook with the thread-local storage.

Parameters#

hook : Any callable object

Returns#

Either a publishable message, or None. The DisplayHook objects must return a message from the __call__ method if they still require the session.send method to be called after transformation. Returning None will halt that execution path, and session.send will not be called.

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

set_parent(parent)#

Set the parent for outbound messages.

topic#

A casting version of the byte string trait.

unregister_hook(hook)#

Un-registers a hook with the thread-local storage.

Parameters#

hookAny callable object which has previously been

registered as a hook.

Returns#

bool - True if the hook was removed, False if it wasn’t

found.

class ipykernel.zmqshell.ZMQInteractiveShell(**kwargs: Any)#

Bases: InteractiveShell

A subclass of InteractiveShell for ZMQ.

ask_exit()#

Engage the exit actions.

autoindent#

A casting version of the boolean trait.

property data_pub#
data_pub_class#

A trait which allows any value.

display_pub_class#

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

displayhook_class#

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

enable_gui(gui)#

Enable a given guil.

exiter#

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_parent()#

Get the parent header.

init_data_pub()#

Delay datapub init until request, for deprecation warnings

init_environment()#

Configure the user’s environment.

init_hooks()#

Initialize hooks.

init_magics()#

Initialize magics.

init_virtualenv()#

Initialize virtual environment.

keepkernel_on_exit = None#
kernel#

A trait which allows any value.

parent_header#

A trait which allows any value.

readline_use#

A casting version of the boolean trait.

run_cell(*args, **kwargs)#

Run a cell.

set_next_input(text, replace=False)#

Send the specified text to the frontend to be presented at the next input cell.

set_parent(parent)#

Set the parent header for associating output with its triggering input

system(cmd)#

Call the given cmd in a subprocess, piping stdout/err

Parameters#

cmdstr

Command to execute (can not end in ‘&’, as background processes are not supported. Should not be a command that expects input other than simple text.

system_piped(cmd)#

Call the given cmd in a subprocess, piping stdout/err

Parameters#

cmdstr

Command to execute (can not end in ‘&’, as background processes are not supported. Should not be a command that expects input other than simple text.

Module contents#