nbclient
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
- breaking nbclient has incrementally dropped support for older Python versions. Version 0.10.2 dropped Python 3.8 support, and 0.10.3 dropped Python 3.9 support. Users on these Python versions must upgrade their Python environment to 3.10+ or use an older `nbclient` version.
- breaking nbclient was extracted from `nbconvert`'s `ExecutePreprocessor`. Code that previously imported `ExecutePreprocessor` or `executenb` from `nbconvert` needs to be updated to use `nbclient` directly.
- gotcha The `timeout` parameter in `NotebookClient` defaults to 30 seconds per cell. For notebooks with long-running cells, this can lead to `TimeoutError`.
Install
-
pip install nbclient
Imports
- NotebookClient
from nbclient import NotebookClient
- nbformat
import nbformat
- execute
from nbclient import execute
Quickstart
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)