Jupyter protocol implementation and client libraries for kernel communication and management
—
Kernel specification discovery, installation, and management system. Handles kernel.json files and kernel discovery across system and user directories, providing APIs for managing available computational kernels.
The KernelSpec class represents a kernel specification containing metadata about how to start and interact with a specific kernel type.
class KernelSpec:
"""Represents a kernel specification."""
@classmethod
def from_resource_dir(cls, resource_dir):
"""
Create a kernel spec from a resource directory.
Parameters:
- resource_dir (str): Path to directory containing kernel.json
Returns:
KernelSpec: Kernel specification instance
"""
def to_dict(self):
"""
Convert kernel spec to dictionary representation.
Returns:
dict: Kernel specification as dictionary
"""
def to_json(self):
"""
Convert kernel spec to JSON string.
Returns:
str: Kernel specification as JSON
"""
# Kernel specification attributes
argv = [] # Command line arguments to start kernel
display_name = '' # Human-readable kernel name
language = '' # Programming language name
interrupt_mode = 'signal' # How to interrupt kernel ('signal' or 'message')
env = {} # Environment variables for kernel
metadata = {} # Additional kernel metadataThe KernelSpecManager class provides discovery, installation, and management of kernel specifications across the system.
class KernelSpecManager:
"""Manages kernel specifications."""
def find_kernel_specs(self):
"""
Find all available kernel specifications.
Returns:
dict: Mapping of kernel names to their spec directory paths
"""
def get_kernel_spec(self, kernel_name):
"""
Get a specific kernel specification by name.
Parameters:
- kernel_name (str): Name of the kernel to retrieve
Returns:
KernelSpec: Kernel specification instance
Raises:
NoSuchKernel: If kernel specification not found
"""
def get_all_specs(self):
"""
Get all kernel specifications with metadata.
Returns:
dict: Mapping of kernel names to spec info dictionaries containing
'spec' (KernelSpec) and 'resource_dir' (str) keys
"""
def install_kernel_spec(self, source_dir, kernel_name=None, user=False,
replace=None, prefix=None):
"""
Install a kernel specification.
Parameters:
- source_dir (str): Directory containing kernel.json and resources
- kernel_name (str): Name for installed kernel (default: dirname)
- user (bool): Install in user directory if True, system if False
- replace (bool): Replace existing kernel if True
- prefix (str): Installation prefix path
Returns:
str: Path where kernel spec was installed
"""
def remove_kernel_spec(self, name):
"""
Remove an installed kernel specification.
Parameters:
- name (str): Name of kernel to remove
Returns:
str: Path of removed kernel spec directory
"""
def install_native_kernel_spec(self, user=False):
"""
Install the native Python kernel specification.
Parameters:
- user (bool): Install in user directory if True
Returns:
None
"""
# Configuration properties
user_kernel_dir = '' # User kernel specifications directory
kernel_dirs = [] # List of kernel search directoriesStandalone functions for working with kernel specifications without requiring a manager instance.
def find_kernel_specs():
"""
Find all available kernel specifications.
Returns:
dict: Mapping of kernel names to spec directory paths
"""
def get_kernel_spec(kernel_name):
"""
Get a specific kernel specification by name.
Parameters:
- kernel_name (str): Name of the kernel
Returns:
KernelSpec: Kernel specification instance
Raises:
NoSuchKernel: If kernel not found
"""
def install_kernel_spec(source_dir, kernel_name=None, user=False,
replace=None, prefix=None):
"""
Install a kernel specification.
Parameters:
- source_dir (str): Source directory with kernel.json
- kernel_name (str): Name for the kernel
- user (bool): Install in user directory
- replace (bool): Replace existing kernel
- prefix (str): Installation prefix
Returns:
str: Installation path
"""
def install_native_kernel_spec(user=False):
"""
Install native Python kernel specification.
Parameters:
- user (bool): Install in user directory
Returns:
None
"""class NoSuchKernel(KeyError):
"""Raised when a requested kernel specification is not found."""Command-line applications for kernel specification management.
class KernelSpecApp:
"""Main application for kernel specification management."""
class ListKernelSpecs:
"""List available kernel specifications."""
class InstallKernelSpec:
"""Install a kernel specification from directory."""
class RemoveKernelSpec:
"""Remove an installed kernel specification."""
class InstallNativeKernelSpec:
"""Install the native Python kernel specification."""
class ListProvisioners:
"""List available kernel provisioners."""from jupyter_client import find_kernel_specs, get_kernel_spec
# Find all available kernel specs
kernel_specs = find_kernel_specs()
print("Available kernels:")
for name, path in kernel_specs.items():
print(f" {name}: {path}")
# Get specific kernel spec
try:
python_spec = get_kernel_spec('python3')
print(f"Python kernel: {python_spec.display_name}")
print(f"Language: {python_spec.language}")
print(f"Command: {python_spec.argv}")
except NoSuchKernel:
print("Python3 kernel not found")from jupyter_client.kernelspec import KernelSpecManager
# Create kernel spec manager
ksm = KernelSpecManager()
# Get all specs with details
all_specs = ksm.get_all_specs()
for name, spec_info in all_specs.items():
spec = spec_info['spec']
resource_dir = spec_info['resource_dir']
print(f"Kernel: {name}")
print(f" Display name: {spec.display_name}")
print(f" Language: {spec.language}")
print(f" Resource dir: {resource_dir}")
print(f" Command: {' '.join(spec.argv)}")
if spec.env:
print(f" Environment: {spec.env}")
print()import os
import json
import tempfile
from jupyter_client import install_kernel_spec
# Create custom kernel specification
kernel_spec = {
"argv": ["python", "-m", "my_custom_kernel", "-f", "{connection_file}"],
"display_name": "My Custom Kernel",
"language": "python",
"interrupt_mode": "signal",
"env": {
"CUSTOM_KERNEL_MODE": "production"
},
"metadata": {
"debugger": True
}
}
# Create temporary directory with kernel.json
with tempfile.TemporaryDirectory() as temp_dir:
kernel_json_path = os.path.join(temp_dir, 'kernel.json')
with open(kernel_json_path, 'w') as f:
json.dump(kernel_spec, f, indent=2)
# Install kernel spec
try:
install_path = install_kernel_spec(
temp_dir,
kernel_name='my-custom-kernel',
user=True, # Install in user directory
replace=True # Replace if exists
)
print(f"Kernel installed at: {install_path}")
except Exception as e:
print(f"Installation failed: {e}")from jupyter_client import get_kernel_spec
# Get kernel spec
spec = get_kernel_spec('python3')
# Examine kernel properties
print(f"Display name: {spec.display_name}")
print(f"Language: {spec.language}")
print(f"Interrupt mode: {spec.interrupt_mode}")
print(f"Command arguments: {spec.argv}")
# Convert to different formats
spec_dict = spec.to_dict()
print(f"As dictionary: {spec_dict}")
spec_json = spec.to_json()
print(f"As JSON: {spec_json}")
# Check for specific capabilities
if 'debugger' in spec.metadata:
print("Kernel supports debugging")
if spec.interrupt_mode == 'signal':
print("Kernel can be interrupted with signals")import os
import tempfile
import json
from jupyter_client.kernelspec import KernelSpec
# Create kernel spec directory structure
with tempfile.TemporaryDirectory() as temp_dir:
# Create kernel.json
kernel_json = {
"argv": ["R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
"display_name": "R",
"language": "R"
}
kernel_json_path = os.path.join(temp_dir, 'kernel.json')
with open(kernel_json_path, 'w') as f:
json.dump(kernel_json, f)
# Create logo files (optional)
logo_32_path = os.path.join(temp_dir, 'logo-32x32.png')
logo_64_path = os.path.join(temp_dir, 'logo-64x64.png')
# Would create actual logo files here
# Load kernel spec from directory
spec = KernelSpec.from_resource_dir(temp_dir)
print(f"Loaded spec: {spec.display_name}")
print(f"Language: {spec.language}")from jupyter_client.kernelspec import KernelSpecManager
ksm = KernelSpecManager()
def list_kernels():
"""List all installed kernels with details."""
specs = ksm.get_all_specs()
print(f"Found {len(specs)} kernel specifications:")
for name, spec_info in specs.items():
spec = spec_info['spec']
print(f"\n{name}:")
print(f" Display Name: {spec.display_name}")
print(f" Language: {spec.language}")
print(f" Location: {spec_info['resource_dir']}")
def remove_kernel(kernel_name):
"""Remove a kernel specification."""
try:
removed_path = ksm.remove_kernel_spec(kernel_name)
print(f"Removed kernel '{kernel_name}' from {removed_path}")
except Exception as e:
print(f"Failed to remove kernel '{kernel_name}': {e}")
def install_native_python():
"""Install native Python kernel."""
ksm.install_native_kernel_spec(user=True)
print("Installed native Python kernel spec")
# Use the functions
list_kernels()
# remove_kernel('old-kernel')
# install_native_python()from jupyter_client.kernelspec import KernelSpecManager
import os
class KernelDiscovery:
def __init__(self):
self.ksm = KernelSpecManager()
def find_kernels_by_language(self, language):
"""Find all kernels for a specific language."""
matching_kernels = []
for name, spec_info in self.ksm.get_all_specs().items():
spec = spec_info['spec']
if spec.language.lower() == language.lower():
matching_kernels.append({
'name': name,
'display_name': spec.display_name,
'resource_dir': spec_info['resource_dir']
})
return matching_kernels
def get_kernel_capabilities(self, kernel_name):
"""Get capabilities of a specific kernel."""
try:
spec = self.ksm.get_kernel_spec(kernel_name)
capabilities = {
'language': spec.language,
'interrupt_mode': spec.interrupt_mode,
'has_debugger': spec.metadata.get('debugger', False),
'environment_vars': list(spec.env.keys()),
'command': spec.argv[0] if spec.argv else None
}
return capabilities
except NoSuchKernel:
return None
def validate_kernel_installation(self, kernel_name):
"""Check if a kernel is properly installed."""
try:
spec = self.ksm.get_kernel_spec(kernel_name)
# Check if command exists
if spec.argv:
command = spec.argv[0]
if not any(os.path.isfile(os.path.join(path, command))
for path in os.environ.get('PATH', '').split(os.pathsep)):
return False, f"Command '{command}' not found in PATH"
return True, "Kernel installation is valid"
except NoSuchKernel:
return False, "Kernel specification not found"
# Use the discovery class
discovery = KernelDiscovery()
# Find Python kernels
python_kernels = discovery.find_kernels_by_language('Python')
print(f"Found {len(python_kernels)} Python kernels:")
for kernel in python_kernels:
print(f" {kernel['name']}: {kernel['display_name']}")
# Check capabilities
if python_kernels:
kernel_name = python_kernels[0]['name']
capabilities = discovery.get_kernel_capabilities(kernel_name)
print(f"\nCapabilities of {kernel_name}:")
for key, value in capabilities.items():
print(f" {key}: {value}")
# Validate installation
valid, message = discovery.validate_kernel_installation(kernel_name)
print(f"\nValidation: {message}")Install with Tessl CLI
npx tessl i tessl/pypi-jupyter-client