| 9 | produces the same file: no execution timestamps (``record_timing=False``), no |
| 10 | Python patch version in the metadata, and deterministic cell ids. Any cell error |
| 11 | stops the run and raises :class:`NotebookExecutionError` after writing the |
| 12 | partially executed notebook, so the traceback can be read in the output file. |
| 13 | |
| 14 | ``run_notebooks.py`` (``just notebooks-run``) calls :func:`execute_notebook` for |
| 15 | every runbook; use this script directly for a single notebook. |
| 16 | """ |
| 17 | |
| 18 | from __future__ import annotations |
| 19 | |
| 20 | import argparse |
| 21 | import os |
| 22 | from pathlib import Path |
| 23 | |
| 24 | import nbformat |
| 25 | from nbclient import NotebookClient |
| 26 | from nbclient.exceptions import CellExecutionError |
| 27 | |
| 28 | DEFAULT_TIMEOUT_S = 600 |
| 29 | KERNEL_NAME = "python3" |
| 30 | |
| 31 | |
| 32 | class NotebookExecutionError(RuntimeError): |
| 33 | """A cell raised; the message carries the notebook name and the cell's traceback.""" |
| 34 | |
| 35 | |
| 36 | def normalize_notebook(nb: nbformat.NotebookNode) -> nbformat.NotebookNode: |
| 37 | """Strip what changes between runs of the same code: timings, versions, random ids.""" |
| 38 | nb.nbformat = 4 |
| 39 | nb.nbformat_minor = 5 |
| 40 | nb.metadata = nbformat.from_dict( |
| 41 | { |
| 42 | "kernelspec": {"display_name": "Python 3", "language": "python", "name": KERNEL_NAME}, |
| 43 | "language_info": {"name": "python"}, |
| 44 | } |
| 45 | ) |
| 46 | for idx, cell in enumerate(nb.cells): |
| 47 | # Positional ids: stable across runs, unlike the random ones nbformat mints. |
| 48 | cell["id"] = f"cell-{idx:02d}" |
| 49 | cell.metadata.pop("execution", None) |
| 50 | cell.metadata.pop("collapsed", None) |