MCPcopy Create free account
hub / github.com/Open-Quant/openquant / execute_notebook

Function execute_notebook

notebooks/python/scripts/execute_notebook_cells.py:11–47  ·  view source on GitHub ↗
(path: Path, out_path: Path | None = None)

Source from the content-addressed store, hash-verified

9produces the same file: no execution timestamps (``record_timing=False``), no
10Python patch version in the metadata, and deterministic cell ids. Any cell error
11stops the run and raises :class:`NotebookExecutionError` after writing the
12partially 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
15every runbook; use this script directly for a single notebook.
16"""
17
18from __future__ import annotations
19
20import argparse
21import os
22from pathlib import Path
23
24import nbformat
25from nbclient import NotebookClient
26from nbclient.exceptions import CellExecutionError
27
28DEFAULT_TIMEOUT_S = 600
29KERNEL_NAME = "python3"
30
31
32class NotebookExecutionError(RuntimeError):
33 """A cell raised; the message carries the notebook name and the cell's traceback."""
34
35
36def 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)

Callers 1

mainFunction · 0.85

Calls 1

appendMethod · 0.80

Tested by

no test coverage detected