nbclient

0.10.4 · active · verified Sat Mar 28

nbclient is a client library for programmatically executing Jupyter notebooks. It was originally spun out of `nbconvert`'s `ExecutePreprocessor` to allow for independent development and easier integration into other tools. It currently supports Python 3.10+ and releases minor versions frequently, typically every few weeks to months.

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a basic Jupyter notebook programmatically, execute it using `nbclient`, and then save the resulting notebook with its outputs. It also includes cleanup of the temporary files.

import nbformat
import os
from nbclient import NotebookClient

# Create a dummy notebook for execution
notebook_content = {
    "cells": [
        {
            "cell_type": "code",
            "source": "a = 1\nb = 2\nprint(a + b)",
            "outputs": [],
            "execution_count": None
        },
        {
            "cell_type": "code",
            "source": "import time\ntime.sleep(0.1)\nprint('Done sleeping')",
            "outputs": [],
            "execution_count": None
        }
    ],
    "metadata": {
        "kernelspec": {
            "display_name": "Python 3",
            "language": "python",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.10.0"
        }
    },
    "nbformat": 4,
    "nbformat_minor": 5
}

input_notebook_path = "my_input_notebook.ipynb"
output_notebook_path = "my_executed_notebook.ipynb"

with open(input_notebook_path, 'w', encoding='utf-8') as f:
    nbformat.write(nbformat.from_dict(notebook_content), f)

# Load the notebook
with open(input_notebook_path) as f:
    nb = nbformat.read(f, as_version=4)

# Configure and execute the notebook
# Adjust timeout for potentially long-running cells or set to None/-1
client = NotebookClient(nb, timeout=600, kernel_name='python3')
try:
    client.execute()
    print(f"Notebook '{input_notebook_path}' executed successfully.")
except Exception as e:
    print(f"Error executing notebook: {e}")

# Save the executed notebook with outputs
with open(output_notebook_path, 'w', encoding='utf-8') as f:
    nbformat.write(nb, f)

print(f"Executed notebook saved to '{output_notebook_path}'.")

# Clean up dummy notebook files
os.remove(input_notebook_path)
os.remove(output_notebook_path)

view raw JSON →