Debian Codegraph @

jupyter_cache/executors/utils.py

raw
1 from pathlib import Path
2 import shutil
3 import traceback
4 from typing import Any, List, Optional, Union
5
6 import attr
7 from nbclient import execute as executenb
8 from nbclient.client import CellExecutionError, CellTimeoutError
9 from nbformat import NotebookNode
10
11 from jupyter_cache.base import CacheBundleIn, ProjectNb
12 from jupyter_cache.cache.main import NbArtifacts
13 from jupyter_cache.utils import Timer, to_relative_paths
14
15
16 @attr.s()
17 class ExecutionResult:
18 nb: NotebookNode = attr.ib()
19 cwd: str = attr.ib()
20 time: float = attr.ib()
21 err: Optional[Union[CellExecutionError, CellTimeoutError]] = attr.ib(default=None)
22 exc_string: Optional[str] = attr.ib(default=None)
23
24
25 def single_nb_execution(
26 nb: NotebookNode,
27 cwd: Optional[str],
28 timeout: Optional[int],
29 allow_errors: bool,
30 meta_override: bool = True,
31 record_timing: bool = False,
32 **kwargs: Any,
33 ) -> ExecutionResult:
34 """Execute notebook in place.
35
36 :param cwd: If supplied, the kernel will run in this directory.
37 :param timeout: The time to wait (in seconds) for output from executions.
38 If a cell execution takes longer, a ``TimeoutError`` is raised.
39 :param allow_errors: If ``False`` when a cell raises an error the
40 execution is stopped and a ``CellExecutionError`` is raised.
41 :param meta_override: If ``True`` then timeout and allow_errors may be overridden
42 by equivalent keys in nb.metadata.execution
43 :param kwargs: Additional keyword arguments to pass to the ``NotebookClient``.
44
45 :returns: The execution time in seconds
46 """
47 if meta_override and "execution" in nb.metadata:
48 if "timeout" in nb.metadata.execution:
49 timeout = nb.metadata.execution.timeout
50 if "allow_errors" in nb.metadata.execution:
51 allow_errors = nb.metadata.execution.allow_errors
52
53 error = exc_string = None
54 # TODO nbclient with record_timing=True will add execution data to each cell
55 timer = Timer()
56 with timer:
57 try:
58 executenb(
59 nb,
60 cwd=cwd,
61 timeout=timeout,
62 allow_errors=allow_errors,
63 record_timing=record_timing,
64 **kwargs,
65 )
66 except (CellExecutionError, CellTimeoutError) as err:
67 error = err
68 exc_string = "".join(traceback.format_exc())
69
70 return ExecutionResult(nb, cwd, timer.last_split, error, exc_string)
71
72
73 def copy_assets(uri: str, assets: List[str], folder: str) -> List[Path]:
74 """Copy notebook assets to the folder the notebook will be executed in."""
75 asset_files = []
76 relative_paths = to_relative_paths(assets, Path(uri).parent)
77 for path, rel_path in zip(assets, relative_paths):
78 temp_file = Path(folder).joinpath(rel_path)
79 temp_file.parent.mkdir(parents=True, exist_ok=True)
80 shutil.copyfile(path, temp_file)
81 asset_files.append(temp_file)
82 return asset_files
83
84
85 def create_cache_bundle(
86 project_nb: ProjectNb,
87 execdir: Optional[str],
88 asset_files: Optional[List[Path]],
89 exec_time: float,
90 exec_tb: Optional[str],
91 ) -> CacheBundleIn:
92 """Create a cache bundle to save."""
93 return CacheBundleIn(
94 project_nb.nb,
95 project_nb.uri,
96 # TODO retrieve assets that have changed file mtime?
97 artifacts=NbArtifacts(
98 [p for p in Path(execdir).glob("**/*") if p not in asset_files],
99 execdir,
100 )
101 if (execdir is not None and asset_files is not None)
102 else None,
103 data={"execution_seconds": exec_time},
104 traceback=exec_tb,
105 )