Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbconvert/preprocessors/execute.py: 34%

38 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

1"""Module containing a preprocessor that executes the code cells 

2and updates outputs""" 

3import typing as t 

4 

5from jupyter_client.manager import KernelManager 

6from nbclient import NotebookClient 

7from nbclient import execute as _execute 

8 

9# Backwards compatability for imported name 

10from nbclient.exceptions import CellExecutionError # noqa 

11 

12# Copyright (c) IPython Development Team. 

13# Distributed under the terms of the Modified BSD License. 

14from nbformat import NotebookNode 

15 

16from .base import Preprocessor 

17 

18 

19def executenb(*args, **kwargs): 

20 """DEPRECATED.""" 

21 from warnings import warn 

22 

23 warn( 

24 "The 'nbconvert.preprocessors.execute.executenb' function was moved to nbclient.execute. " 

25 "We recommend importing that library directly.", 

26 FutureWarning, 

27 stacklevel=2, 

28 ) 

29 return _execute(*args, **kwargs) 

30 

31 

32# We inherit from both classes to allow for traitlets to resolve as they did pre-6.0. 

33# This unfortunately makes for some ugliness around initialization as NotebookClient 

34# assumes it's a constructed class with a nb object that we have to hack around. 

35class ExecutePreprocessor(Preprocessor, NotebookClient): 

36 """ 

37 Executes all the cells in a notebook 

38 """ 

39 

40 def __init__(self, **kw): 

41 """Initialize the preprocessor.""" 

42 nb = kw.get("nb") 

43 if nb is None: 

44 nb = NotebookNode() 

45 Preprocessor.__init__(self, nb=nb, **kw) 

46 NotebookClient.__init__(self, nb, **kw) 

47 

48 def _check_assign_resources(self, resources): 

49 if resources or not hasattr(self, "resources"): 

50 self.resources = resources 

51 

52 def preprocess( 

53 self, nb: NotebookNode, resources: t.Any = None, km: t.Optional[KernelManager] = None 

54 ) -> t.Tuple[NotebookNode, dict]: 

55 """ 

56 Preprocess notebook executing each code cell. 

57 

58 The input argument *nb* is modified in-place. 

59 

60 Note that this function recalls NotebookClient.__init__, which may look wrong. 

61 However since the preprocess call acts line an init on execution state it's expected. 

62 Therefore, we need to capture it here again to properly reset because traitlet 

63 assignments are not passed. There is a risk if traitlets apply any side effects for 

64 dual init. 

65 The risk should be manageable, and this approach minimizes side-effects relative 

66 to other alternatives. 

67 

68 One alternative but rejected implementation would be to copy the client's init internals 

69 which has already gotten out of sync with nbclient 0.5 release before nbconvert 6.0 released. 

70 

71 Parameters 

72 ---------- 

73 nb : NotebookNode 

74 Notebook being executed. 

75 resources : dictionary (optional) 

76 Additional resources used in the conversion process. For example, 

77 passing ``{'metadata': {'path': run_path}}`` sets the 

78 execution path to ``run_path``. 

79 km: KernelManager (optional) 

80 Optional kernel manager. If none is provided, a kernel manager will 

81 be created. 

82 

83 Returns 

84 ------- 

85 nb : NotebookNode 

86 The executed notebook. 

87 resources : dictionary 

88 Additional resources used in the conversion process. 

89 """ 

90 NotebookClient.__init__(self, nb, km) 

91 self.reset_execution_trackers() 

92 self._check_assign_resources(resources) 

93 

94 with self.setup_kernel(): 

95 assert self.kc # noqa 

96 info_msg = self.wait_for_reply(self.kc.kernel_info()) 

97 assert info_msg # noqa 

98 self.nb.metadata["language_info"] = info_msg["content"]["language_info"] 

99 for index, cell in enumerate(self.nb.cells): 

100 self.preprocess_cell(cell, resources, index) 

101 self.set_widgets_metadata() 

102 

103 return self.nb, self.resources 

104 

105 def preprocess_cell(self, cell, resources, index): 

106 """ 

107 Override if you want to apply some preprocessing to each cell. 

108 Must return modified cell and resource dictionary. 

109 

110 Parameters 

111 ---------- 

112 cell : NotebookNode cell 

113 Notebook cell being processed 

114 resources : dictionary 

115 Additional resources used in the conversion process. Allows 

116 preprocessors to pass variables into the Jinja engine. 

117 index : int 

118 Index of the cell being processed 

119 """ 

120 self._check_assign_resources(resources) 

121 cell = self.execute_cell(cell, index, store_history=True) 

122 return cell, self.resources