Jupyter Client

8.8.0 · active · verified Sat Mar 28

Jupyter Client (`jupyter_client`) provides the reference implementation of the Jupyter protocol, offering Python APIs for starting, managing, and communicating with Jupyter kernels. It also includes the `jupyter kernelspec` entrypoint for installing kernel specifications. Currently at version 8.8.0, the library maintains an active development pace with several releases annually to introduce enhancements and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically start a Jupyter kernel, execute Python code, and capture its output using `jupyter_client`'s blocking API. It initializes a `KernelManager`, obtains a `BlockingKernelClient`, and sends code for execution, then processes the incoming messages until the kernel returns to an idle state. Remember to call `stop_channels()` and `shutdown_kernel()` for proper cleanup.

import time
from jupyter_client import KernelManager
from queue import Empty

def main():
    # Start a Python kernel
    km = KernelManager(kernel_name='python3')
    km.start_kernel()

    # Get a blocking client to interact with the kernel
    kc = km.client(blocking=True)
    kc.start_channels()

    try:
        # Ensure the client is connected and ready
        kc.wait_for_ready(timeout=60)

        # Execute some code
        code = 'print("Hello from Jupyter Kernel!")\na = 10\nprint(f"a is {a}")'
        msg_id = kc.execute(code)

        # Process IOPub messages until execution state is idle or timeout
        while True:
            try:
                msg = kc.get_iopub_msg(timeout=1)
                msg_type = msg['msg_type']
                content = msg['content']

                if msg_type == 'stream' and content['name'] == 'stdout':
                    print(f"[Kernel Output]: {content['text'].strip()}")
                elif msg_type == 'status' and content['execution_state'] == 'idle':
                    print("[Kernel Status]: Idle")
                    break
            except Empty:
                # No messages in queue, continue waiting for idle status
                continue
            except Exception as e:
                print(f"Error receiving IOPub message: {e}")
                break

    finally:
        # Clean up: stop channels and shut down the kernel
        kc.stop_channels()
        km.shutdown_kernel()
        print("Kernel shutdown complete.")

if __name__ == '__main__':
    main()

view raw JSON →