Introduction to jupyter-client
The jupyter-client library is a cornerstone of the Jupyter ecosystem, enabling programmatic interaction with kernels in the Jupyter architecture. From sending and receiving messages to managing kernels and sessions, jupyter-client
provides a robust API for developers looking to integrate interactive computational environments into their applications.
Key Features of jupyter-client
- Manage Jupyter kernels programmatically.
- Interact with kernel sessions easily using a messaging interface.
- Send code for execution and retrieve outputs in real-time.
- Customizable and extensible to various application requirements.
APIs and Examples
To make the most of jupyter-client
, let’s explore its most useful APIs with practical examples to help you quickly build interactive applications.
1. Starting and Managing Kernels
The KernelManager
API lets you start, stop, and manage kernels. Here is how you can start a kernel:
from jupyter_client import KernelManager km = KernelManager() km.start_kernel() print(f"Kernel started with PID: {km.kernel.pid}")
You can also restart or interrupt a kernel:
# Restart the kernel km.restart_kernel() print("Kernel restarted") # Interrupt the kernel km.interrupt_kernel() print("Kernel interrupted")
2. Sending Code for Execution
Use the KernelClient
API to send and execute code in the kernel:
kc = km.client() kc.start_channels() # Send code to the kernel kc.execute("a = 5\nb = 10\nsum_ab = a + b\nsum_ab") # Retrieve the output while True: msg = kc.get_iopub_msg() if msg['msg_type'] == 'execute_result': print("Execution result:", msg['content']['data']['text/plain']) break
3. Inspecting Variables
The KernelClient
API supports introspecting variables using the kernel:
query = "sum_ab" kc.inspect(query, cursor_pos=len(query)) while True: msg = kc.get_shell_msg() if msg['msg_type'] == 'inspect_reply': print("Inspection result:", msg['content']['data']) break
4. Handling Input and Output
Respond to input requests from the kernel for interactive workflows:
kc.execute("input('Enter your name: ')") while True: msg = kc.get_iopub_msg() if msg['msg_type'] == 'stream': print("Kernel stream output:", msg['content']['text']) break
5. Managing Kernel Sessions
jupyter-client
supports session management for advanced use cases:
from jupyter_client.session import Session session = Session() msg = session.msg("execute_request", content={"code": "x = 42"}) print("Message to kernel:", msg)
Building an Interactive Application
Here’s an example that combines multiple APIs to create an application where users can interactively execute Python code:
import asyncio from jupyter_client import KernelManager async def interactive_console(): # Start kernel manager km = KernelManager() km.start_kernel() kc = km.client() kc.start_channels() print("Welcome to the Interactive Python Console. Type 'exit' to quit.") while True: code = input(">>> ") if code.strip().lower() == 'exit': break kc.execute(code) # Fetch and print output while True: msg = kc.get_iopub_msg() if msg['msg_type'] in ['execute_result', 'stream']: print(msg['content']['text']) break # Shut down the kernel kc.stop_channels() km.shutdown_kernel() print("Kernel shut down. Goodbye!") asyncio.run(interactive_console())
Conclusion
With jupyter-client
, you gain powerful tools to manage, customize, and interact with Jupyter kernels. Whether you’re building an interactive application or extending Jupyter’s capabilities, this library provides the flexibility and reliability you need.
Start experimenting with jupyter-client
today to unlock its full potential in your projects!