CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-ipykernel

IPython Kernel for Jupyter - provides the core communication layer between Jupyter frontends and the Python interpreter

Pending
Overview
Eval results
Files

kernel-embedding.mddocs/

Kernel Embedding

Tools for embedding IPython kernels directly into Python applications and interactive sessions, enabling kernel functionality within existing codebases for debugging, interactive development, and creating custom interactive environments.

Capabilities

Kernel Embedding Function

Primary function for embedding a kernel into the current Python context.

def embed_kernel(module=None, local_ns=None, **kwargs):
    """
    Embed and start an IPython kernel in the current scope.
    
    This creates an interactive kernel that can be connected to by
    Jupyter frontends while maintaining access to the local variables
    and execution context where it was called.
    
    Parameters:
    - module (module, optional): Module to use as __main__ context
    - local_ns (dict, optional): Local namespace for kernel execution
    - **kwargs: Additional kernel configuration options including:
        - user_ns (dict): User namespace for kernel
        - connection_file (str): Path to connection file
        - ip (str): IP address for kernel connections
        - shell_port (int): Port for shell messages
        - iopub_port (int): Port for IOPub messages
        - stdin_port (int): Port for stdin messages
        - control_port (int): Port for control messages
        - hb_port (int): Port for heartbeat
    
    Returns:
    None (starts kernel event loop, blocks until shutdown)
    
    Example:
    ```python
    import ipykernel
    
    # Embed kernel with current local variables
    x = 42
    y = "hello"
    ipykernel.embed_kernel()  # x and y available in kernel
    ```
    """

Usage Examples

Basic Kernel Embedding

from ipykernel import embed_kernel

def my_function():
    x = 42
    data = [1, 2, 3, 4, 5]
    
    print("Starting embedded kernel...")
    print("Variables 'x' and 'data' are available in the kernel")
    
    # Embed kernel with access to local variables
    embed_kernel()  # Blocks here until kernel shutdown

# Call the function
my_function()

Embedding with Custom Namespace

from ipykernel import embed_kernel

# Create custom namespace for kernel
custom_ns = {
    'config': {'debug': True, 'max_items': 100},
    'utils': {'format_data': lambda x: f"Data: {x}"},
    'data_store': []
}

print("Embedding kernel with custom utilities...")
embed_kernel(user_ns=custom_ns)

Debugging with Embedded Kernel

from ipykernel import embed_kernel

def complex_algorithm(data):
    """Complex function that might need debugging."""
    processed = []
    
    for i, item in enumerate(data):
        # Complex processing logic
        result = item * 2 + i
        processed.append(result)
        
        # Embed kernel for debugging at specific point
        if len(processed) == 3:
            print("Debugging checkpoint reached")
            print(f"Current state: processed={processed}")
            embed_kernel()  # Debug here with full context
    
    return processed

# Run with debugging
result = complex_algorithm([10, 20, 30, 40, 50])

Interactive Development Environment

from ipykernel import embed_kernel
import sys
import os

class InteractiveDevelopment:
    """Custom interactive development environment."""
    
    def __init__(self, project_path):
        self.project_path = project_path
        self.modules_loaded = []
        
        # Add project to Python path
        if project_path not in sys.path:
            sys.path.insert(0, project_path)
    
    def load_module(self, module_name):
        """Load and track project modules."""
        try:
            module = __import__(module_name)
            self.modules_loaded.append(module_name)
            return module
        except ImportError as e:
            print(f"Failed to load {module_name}: {e}")
            return None
    
    def start_interactive_session(self):
        """Start embedded kernel with development context."""
        # Create development namespace
        dev_ns = {
            'project_path': self.project_path,
            'load_module': self.load_module,
            'modules_loaded': self.modules_loaded,
            'reload_module': lambda name: __import__(name, fromlist=[''], 
                                                   level=0).__dict__.update(
                                                       __import__(name, fromlist=[''], level=0).__dict__
                                                   )
        }
        
        print(f"Starting interactive development session for: {self.project_path}")
        print("Available tools: load_module(), reload_module(), modules_loaded")
        
        embed_kernel(user_ns=dev_ns)

# Usage
dev_env = InteractiveDevelopment('/path/to/my/project')
dev_env.start_interactive_session()

Embedding with Connection Configuration

from ipykernel import embed_kernel
import tempfile
import os

# Create temporary connection file
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
    connection_file = f.name

try:
    print(f"Starting kernel with connection file: {connection_file}")
    
    # Embed with specific connection configuration
    embed_kernel(
        connection_file=connection_file,
        ip='127.0.0.1',
        shell_port=54321,
        iopub_port=54322,
        stdin_port=54323,
        control_port=54324,
        hb_port=54325
    )
    
finally:
    # Cleanup connection file
    if os.path.exists(connection_file):
        os.unlink(connection_file)

Class-Based Embedding

from ipykernel import embed_kernel

class DataProcessor:
    """Example class with embedded debugging capabilities."""
    
    def __init__(self, config):
        self.config = config
        self.processed_items = []
        self.debug_mode = config.get('debug', False)
    
    def process_data(self, data):
        """Process data with optional embedded debugging."""
        for item in data:
            processed = self._process_item(item)
            self.processed_items.append(processed)
            
            # Embed kernel for debugging if enabled
            if self.debug_mode and len(self.processed_items) % 10 == 0:
                print(f"Processed {len(self.processed_items)} items")
                self._debug_checkpoint()
    
    def _process_item(self, item):
        """Process individual item."""
        return {'original': item, 'processed': item * 2}
    
    def _debug_checkpoint(self):
        """Embed kernel with class context."""
        # Create namespace with class attributes
        debug_ns = {
            'processor': self,
            'config': self.config,
            'processed_items': self.processed_items,
            'item_count': len(self.processed_items)
        }
        
        print("Debug checkpoint - 'processor' object available")
        embed_kernel(user_ns=debug_ns)

# Usage with debugging enabled
processor = DataProcessor({'debug': True, 'batch_size': 100})
processor.process_data(range(25))

Module Context Embedding

from ipykernel import embed_kernel
import sys

# Save current module context
current_module = sys.modules[__name__]

def embed_with_module_context():
    """Embed kernel with current module as __main__."""
    print("Embedding kernel with module context")
    print(f"Current module: {current_module}")
    
    # Embed with module context
    embed_kernel(module=current_module)

# This makes the current module available as __main__ in kernel
embed_with_module_context()

Install with Tessl CLI

npx tessl i tessl/pypi-ipykernel

docs

communication-framework.md

connection-management.md

core-kernel.md

data-utilities.md

gui-integration.md

in-process-kernels.md

index.md

io-streaming.md

kernel-application.md

kernel-embedding.md

matplotlib-integration.md

tile.json