client.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. """nbclient implementation."""
  2. from __future__ import annotations
  3. import asyncio
  4. import atexit
  5. import base64
  6. import collections
  7. import datetime
  8. import re
  9. import signal
  10. import typing as t
  11. from contextlib import asynccontextmanager, contextmanager
  12. from queue import Empty
  13. from textwrap import dedent
  14. from time import monotonic
  15. from jupyter_client.client import KernelClient
  16. from jupyter_client.manager import KernelManager
  17. from nbformat import NotebookNode
  18. from nbformat.v4 import output_from_msg
  19. from traitlets import Any, Bool, Callable, Dict, Enum, Integer, List, Type, Unicode, default
  20. from traitlets.config.configurable import LoggingConfigurable
  21. from .exceptions import (
  22. CellControlSignal,
  23. CellExecutionComplete,
  24. CellExecutionError,
  25. CellTimeoutError,
  26. DeadKernelError,
  27. )
  28. from .output_widget import OutputWidget
  29. from .util import ensure_async, run_hook, run_sync
  30. _RGX_CARRIAGERETURN = re.compile(r".*\r(?=[^\n])")
  31. _RGX_BACKSPACE = re.compile(r"[^\n]\b")
  32. # mypy: disable-error-code="no-untyped-call"
  33. def timestamp(msg: dict[str, t.Any] | None = None) -> str:
  34. """Get the timestamp for a message."""
  35. if msg and "header" in msg: # The test mocks don't provide a header, so tolerate that
  36. msg_header = msg["header"]
  37. if "date" in msg_header and isinstance(msg_header["date"], datetime.datetime):
  38. try:
  39. # reformat datetime into expected format
  40. formatted_time = datetime.datetime.strftime(
  41. msg_header["date"], "%Y-%m-%dT%H:%M:%S.%fZ"
  42. )
  43. if (
  44. formatted_time
  45. ): # docs indicate strftime may return empty string, so let's catch that too
  46. return formatted_time
  47. except Exception: # noqa
  48. pass # fallback to a local time
  49. return datetime.datetime.utcnow().isoformat() + "Z"
  50. class NotebookClient(LoggingConfigurable):
  51. """
  52. Encompasses a Client for executing cells in a notebook
  53. """
  54. timeout = Integer(
  55. None,
  56. allow_none=True,
  57. help=dedent(
  58. """
  59. The time to wait (in seconds) for output from executions.
  60. If a cell execution takes longer, a TimeoutError is raised.
  61. ``None`` or ``-1`` will disable the timeout. If ``timeout_func`` is set,
  62. it overrides ``timeout``.
  63. """
  64. ),
  65. ).tag(config=True)
  66. timeout_func: t.Callable[..., int | None] | None = Any( # type:ignore[assignment]
  67. default_value=None,
  68. allow_none=True,
  69. help=dedent(
  70. """
  71. A callable which, when given the cell source as input,
  72. returns the time to wait (in seconds) for output from cell
  73. executions. If a cell execution takes longer, a TimeoutError
  74. is raised.
  75. Returning ``None`` or ``-1`` will disable the timeout for the cell.
  76. Not setting ``timeout_func`` will cause the client to
  77. default to using the ``timeout`` trait for all cells. The
  78. ``timeout_func`` trait overrides ``timeout`` if it is not ``None``.
  79. """
  80. ),
  81. ).tag(config=True)
  82. interrupt_on_timeout = Bool(
  83. False,
  84. help=dedent(
  85. """
  86. If execution of a cell times out, interrupt the kernel and
  87. continue executing other cells rather than throwing an error and
  88. stopping.
  89. """
  90. ),
  91. ).tag(config=True)
  92. error_on_timeout = Dict(
  93. default_value=None,
  94. allow_none=True,
  95. help=dedent(
  96. """
  97. If a cell execution was interrupted after a timeout, don't wait for
  98. the execute_reply from the kernel (e.g. KeyboardInterrupt error).
  99. Instead, return an execute_reply with the given error, which should
  100. be of the following form::
  101. {
  102. 'ename': str, # Exception name, as a string
  103. 'evalue': str, # Exception value, as a string
  104. 'traceback': list(str), # traceback frames, as strings
  105. }
  106. """
  107. ),
  108. ).tag(config=True)
  109. startup_timeout = Integer(
  110. 60,
  111. help=dedent(
  112. """
  113. The time to wait (in seconds) for the kernel to start.
  114. If kernel startup takes longer, a RuntimeError is
  115. raised.
  116. """
  117. ),
  118. ).tag(config=True)
  119. allow_errors = Bool(
  120. False,
  121. help=dedent(
  122. """
  123. If ``False`` (default), when a cell raises an error the
  124. execution is stopped and a ``CellExecutionError``
  125. is raised, except if the error name is in
  126. ``allow_error_names``.
  127. If ``True``, execution errors are ignored and the execution
  128. is continued until the end of the notebook. Output from
  129. exceptions is included in the cell output in both cases.
  130. """
  131. ),
  132. ).tag(config=True)
  133. allow_error_names = List(
  134. Unicode(),
  135. help=dedent(
  136. """
  137. List of error names which won't stop the execution. Use this if the
  138. ``allow_errors`` option it too general and you want to allow only
  139. specific kinds of errors.
  140. """
  141. ),
  142. ).tag(config=True)
  143. force_raise_errors = Bool(
  144. False,
  145. help=dedent(
  146. """
  147. If False (default), errors from executing the notebook can be
  148. allowed with a ``raises-exception`` tag on a single cell, or the
  149. ``allow_errors`` or ``allow_error_names`` configurable options for
  150. all cells. An allowed error will be recorded in notebook output, and
  151. execution will continue. If an error occurs when it is not
  152. explicitly allowed, a ``CellExecutionError`` will be raised.
  153. If True, ``CellExecutionError`` will be raised for any error that occurs
  154. while executing the notebook. This overrides the ``allow_errors``
  155. and ``allow_error_names`` options and the ``raises-exception`` cell
  156. tag.
  157. """
  158. ),
  159. ).tag(config=True)
  160. skip_cells_with_tag = Unicode(
  161. "skip-execution",
  162. help=dedent(
  163. """
  164. Name of the cell tag to use to denote a cell that should be skipped.
  165. """
  166. ),
  167. ).tag(config=True)
  168. extra_arguments = List(Unicode()).tag(config=True)
  169. kernel_name = Unicode(
  170. "",
  171. help=dedent(
  172. """
  173. Name of kernel to use to execute the cells.
  174. If not set, use the kernel_spec embedded in the notebook.
  175. """
  176. ),
  177. ).tag(config=True)
  178. raise_on_iopub_timeout = Bool(
  179. False,
  180. help=dedent(
  181. """
  182. If ``False`` (default), then the kernel will continue waiting for
  183. iopub messages until it receives a kernel idle message, or until a
  184. timeout occurs, at which point the currently executing cell will be
  185. skipped. If ``True``, then an error will be raised after the first
  186. timeout. This option generally does not need to be used, but may be
  187. useful in contexts where there is the possibility of executing
  188. notebooks with memory-consuming infinite loops.
  189. """
  190. ),
  191. ).tag(config=True)
  192. store_widget_state = Bool(
  193. True,
  194. help=dedent(
  195. """
  196. If ``True`` (default), then the state of the Jupyter widgets created
  197. at the kernel will be stored in the metadata of the notebook.
  198. """
  199. ),
  200. ).tag(config=True)
  201. record_timing = Bool(
  202. True,
  203. help=dedent(
  204. """
  205. If ``True`` (default), then the execution timings of each cell will
  206. be stored in the metadata of the notebook.
  207. """
  208. ),
  209. ).tag(config=True)
  210. iopub_timeout = Integer(
  211. 4,
  212. allow_none=False,
  213. help=dedent(
  214. """
  215. The time to wait (in seconds) for IOPub output. This generally
  216. doesn't need to be set, but on some slow networks (such as CI
  217. systems) the default timeout might not be long enough to get all
  218. messages.
  219. """
  220. ),
  221. ).tag(config=True)
  222. shell_timeout_interval = Integer(
  223. 5,
  224. allow_none=False,
  225. help=dedent(
  226. """
  227. The time to wait (in seconds) for Shell output before retrying.
  228. This generally doesn't need to be set, but if one needs to check
  229. for dead kernels at a faster rate this can help.
  230. """
  231. ),
  232. ).tag(config=True)
  233. shutdown_kernel = Enum(
  234. ["graceful", "immediate"],
  235. default_value="graceful",
  236. help=dedent(
  237. """
  238. If ``graceful`` (default), then the kernel is given time to clean
  239. up after executing all cells, e.g., to execute its ``atexit`` hooks.
  240. If ``immediate``, then the kernel is signaled to immediately
  241. terminate.
  242. """
  243. ),
  244. ).tag(config=True)
  245. ipython_hist_file = Unicode(
  246. default_value=":memory:",
  247. help="""Path to file to use for SQLite history database for an IPython kernel.
  248. The specific value ``:memory:`` (including the colon
  249. at both end but not the back ticks), avoids creating a history file. Otherwise, IPython
  250. will create a history file for each kernel.
  251. When running kernels simultaneously (e.g. via multiprocessing) saving history a single
  252. SQLite file can result in database errors, so using ``:memory:`` is recommended in
  253. non-interactive contexts.
  254. """,
  255. ).tag(config=True)
  256. kernel_manager_class = Type(
  257. config=True, klass=KernelManager, help="The kernel manager class to use."
  258. )
  259. on_notebook_start = Callable(
  260. default_value=None,
  261. allow_none=True,
  262. help=dedent(
  263. """
  264. A callable which executes after the kernel manager and kernel client are setup, and
  265. cells are about to execute.
  266. Called with kwargs ``notebook``.
  267. """
  268. ),
  269. ).tag(config=True)
  270. on_notebook_complete = Callable(
  271. default_value=None,
  272. allow_none=True,
  273. help=dedent(
  274. """
  275. A callable which executes after the kernel is cleaned up.
  276. Called with kwargs ``notebook``.
  277. """
  278. ),
  279. ).tag(config=True)
  280. on_notebook_error = Callable(
  281. default_value=None,
  282. allow_none=True,
  283. help=dedent(
  284. """
  285. A callable which executes when the notebook encounters an error.
  286. Called with kwargs ``notebook``.
  287. """
  288. ),
  289. ).tag(config=True)
  290. on_cell_start = Callable(
  291. default_value=None,
  292. allow_none=True,
  293. help=dedent(
  294. """
  295. A callable which executes before a cell is executed and before non-executing cells
  296. are skipped.
  297. Called with kwargs ``cell`` and ``cell_index``.
  298. """
  299. ),
  300. ).tag(config=True)
  301. on_cell_execute = Callable(
  302. default_value=None,
  303. allow_none=True,
  304. help=dedent(
  305. """
  306. A callable which executes just before a code cell is executed.
  307. Called with kwargs ``cell`` and ``cell_index``.
  308. """
  309. ),
  310. ).tag(config=True)
  311. on_cell_complete = Callable(
  312. default_value=None,
  313. allow_none=True,
  314. help=dedent(
  315. """
  316. A callable which executes after a cell execution is complete. It is
  317. called even when a cell results in a failure.
  318. Called with kwargs ``cell`` and ``cell_index``.
  319. """
  320. ),
  321. ).tag(config=True)
  322. on_cell_executed = Callable(
  323. default_value=None,
  324. allow_none=True,
  325. help=dedent(
  326. """
  327. A callable which executes just after a code cell is executed, whether
  328. or not it results in an error.
  329. Called with kwargs ``cell``, ``cell_index`` and ``execute_reply``.
  330. """
  331. ),
  332. ).tag(config=True)
  333. on_cell_error = Callable(
  334. default_value=None,
  335. allow_none=True,
  336. help=dedent(
  337. """
  338. A callable which executes when a cell execution results in an error.
  339. This is executed even if errors are suppressed with ``cell_allows_errors``.
  340. Called with kwargs ``cell`, ``cell_index`` and ``execute_reply``.
  341. """
  342. ),
  343. ).tag(config=True)
  344. @default("kernel_manager_class")
  345. def _kernel_manager_class_default(self) -> type[KernelManager]:
  346. """Use a dynamic default to avoid importing jupyter_client at startup"""
  347. from jupyter_client import AsyncKernelManager # type:ignore[attr-defined]
  348. return AsyncKernelManager
  349. _display_id_map: dict[str, t.Any] = Dict( # type:ignore[assignment]
  350. help=dedent(
  351. """
  352. mapping of locations of outputs with a given display_id
  353. tracks cell index and output index within cell.outputs for
  354. each appearance of the display_id
  355. {
  356. 'display_id': {
  357. cell_idx: [output_idx,]
  358. }
  359. }
  360. """
  361. )
  362. )
  363. display_data_priority = List(
  364. [
  365. "text/html",
  366. "application/pdf",
  367. "text/latex",
  368. "image/svg+xml",
  369. "image/png",
  370. "image/jpeg",
  371. "text/markdown",
  372. "text/plain",
  373. ],
  374. help="""
  375. An ordered list of preferred output type, the first
  376. encountered will usually be used when converting discarding
  377. the others.
  378. """,
  379. ).tag(config=True)
  380. resources: dict[str, t.Any] = Dict( # type:ignore[assignment]
  381. help=dedent(
  382. """
  383. Additional resources used in the conversion process. For example,
  384. passing ``{'metadata': {'path': run_path}}`` sets the
  385. execution path to ``run_path``.
  386. """
  387. )
  388. )
  389. coalesce_streams = Bool(
  390. help=dedent(
  391. """
  392. Merge all stream outputs with shared names into single streams.
  393. """
  394. )
  395. )
  396. def __init__(self, nb: NotebookNode, km: KernelManager | None = None, **kw: t.Any) -> None:
  397. """Initializes the execution manager.
  398. Parameters
  399. ----------
  400. nb : NotebookNode
  401. Notebook being executed.
  402. km : KernelManager (optional)
  403. Optional kernel manager. If none is provided, a kernel manager will
  404. be created.
  405. """
  406. super().__init__(**kw)
  407. self.nb: NotebookNode = nb
  408. self.km: KernelManager | None = km
  409. self.owns_km: bool = km is None # whether the NotebookClient owns the kernel manager
  410. self.kc: KernelClient | None = None
  411. self.reset_execution_trackers()
  412. self.widget_registry: dict[str, dict[str, t.Any]] = {
  413. "@jupyter-widgets/output": {"OutputModel": OutputWidget}
  414. }
  415. # comm_open_handlers should return an object with a .handle_msg(msg) method or None
  416. self.comm_open_handlers: dict[str, t.Any] = {
  417. "jupyter.widget": self.on_comm_open_jupyter_widget
  418. }
  419. def reset_execution_trackers(self) -> None:
  420. """Resets any per-execution trackers."""
  421. self.task_poll_for_reply: asyncio.Future[t.Any] | None = None
  422. self.code_cells_executed = 0
  423. self._display_id_map = {}
  424. self.widget_state: dict[str, dict[str, t.Any]] = {}
  425. self.widget_buffers: dict[str, dict[tuple[str, ...], dict[str, str]]] = {}
  426. # maps to list of hooks, where the last is used, this is used
  427. # to support nested use of output widgets.
  428. self.output_hook_stack: dict[str, list[OutputWidget]] = collections.defaultdict(list)
  429. # our front-end mimicking Output widgets
  430. self.comm_objects: dict[str, t.Any] = {}
  431. def create_kernel_manager(self) -> KernelManager:
  432. """Creates a new kernel manager.
  433. Returns
  434. -------
  435. km : KernelManager
  436. Kernel manager whose client class is asynchronous.
  437. """
  438. if not self.kernel_name:
  439. kn = self.nb.metadata.get("kernelspec", {}).get("name")
  440. if kn is not None:
  441. self.kernel_name = kn
  442. if not self.kernel_name:
  443. self.km = self.kernel_manager_class(config=self.config)
  444. else:
  445. self.km = self.kernel_manager_class(kernel_name=self.kernel_name, config=self.config)
  446. assert self.km is not None
  447. return self.km
  448. async def _async_cleanup_kernel(self) -> None:
  449. assert self.km is not None
  450. now = self.shutdown_kernel == "immediate"
  451. try:
  452. # Queue the manager to kill the process, and recover gracefully if it's already dead.
  453. if await ensure_async(self.km.is_alive()):
  454. await ensure_async(self.km.shutdown_kernel(now=now))
  455. except RuntimeError as e:
  456. # The error isn't specialized, so we have to check the message
  457. if "No kernel is running!" not in str(e):
  458. raise
  459. finally:
  460. # Remove any state left over even if we failed to stop the kernel
  461. await ensure_async(self.km.cleanup_resources())
  462. if getattr(self, "kc", None) and self.kc is not None:
  463. await ensure_async(self.kc.stop_channels()) # type:ignore[func-returns-value]
  464. self.kc = None
  465. self.km = None
  466. _cleanup_kernel = run_sync(_async_cleanup_kernel)
  467. async def async_start_new_kernel(self, **kwargs: t.Any) -> None:
  468. """Creates a new kernel.
  469. Parameters
  470. ----------
  471. kwargs :
  472. Any options for ``self.kernel_manager_class.start_kernel()``. Because
  473. that defaults to AsyncKernelManager, this will likely include options
  474. accepted by ``AsyncKernelManager.start_kernel()``, which includes ``cwd``.
  475. """
  476. assert self.km is not None
  477. resource_path = self.resources.get("metadata", {}).get("path") or None
  478. if resource_path and "cwd" not in kwargs:
  479. kwargs["cwd"] = resource_path
  480. has_history_manager_arg = any(
  481. arg.startswith("--HistoryManager.hist_file") for arg in self.extra_arguments
  482. )
  483. if (
  484. hasattr(self.km, "ipykernel")
  485. and self.km.ipykernel
  486. and self.ipython_hist_file
  487. and not has_history_manager_arg
  488. ):
  489. self.extra_arguments += [f"--HistoryManager.hist_file={self.ipython_hist_file}"]
  490. await ensure_async(self.km.start_kernel(extra_arguments=self.extra_arguments, **kwargs))
  491. start_new_kernel = run_sync(async_start_new_kernel)
  492. async def async_start_new_kernel_client(self) -> KernelClient:
  493. """Creates a new kernel client.
  494. Returns
  495. -------
  496. kc : KernelClient
  497. Kernel client as created by the kernel manager ``km``.
  498. """
  499. assert self.km is not None
  500. try:
  501. self.kc = self.km.client()
  502. await ensure_async(self.kc.start_channels()) # type:ignore[func-returns-value]
  503. await ensure_async(self.kc.wait_for_ready(timeout=self.startup_timeout))
  504. except Exception as e:
  505. self.log.error(
  506. "Error occurred while starting new kernel client for kernel {}: {}".format(
  507. getattr(self.km, "kernel_id", None), str(e)
  508. )
  509. )
  510. await self._async_cleanup_kernel()
  511. raise
  512. self.kc.allow_stdin = False
  513. await run_hook(self.on_notebook_start, notebook=self.nb)
  514. return self.kc
  515. start_new_kernel_client = run_sync(async_start_new_kernel_client)
  516. @contextmanager
  517. def setup_kernel(self, **kwargs: t.Any) -> t.Generator[None, None, None]:
  518. """
  519. Context manager for setting up the kernel to execute a notebook.
  520. The assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``).
  521. When control returns from the yield it stops the client's zmq channels, and shuts
  522. down the kernel.
  523. """
  524. # by default, cleanup the kernel client if we own the kernel manager
  525. # and keep it alive if we don't
  526. cleanup_kc = kwargs.pop("cleanup_kc", self.owns_km)
  527. # Can't use run_until_complete on an asynccontextmanager function :(
  528. if self.km is None:
  529. self.km = self.create_kernel_manager()
  530. if not self.km.has_kernel:
  531. self.start_new_kernel(**kwargs)
  532. if self.kc is None:
  533. self.start_new_kernel_client()
  534. try:
  535. yield
  536. finally:
  537. if cleanup_kc:
  538. self._cleanup_kernel()
  539. @asynccontextmanager
  540. async def async_setup_kernel(self, **kwargs: t.Any) -> t.AsyncGenerator[None, None]:
  541. """
  542. Context manager for setting up the kernel to execute a notebook.
  543. This assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``).
  544. When control returns from the yield it stops the client's zmq channels, and shuts
  545. down the kernel.
  546. Handlers for SIGINT and SIGTERM are also added to cleanup in case of unexpected shutdown.
  547. """
  548. # by default, cleanup the kernel client if we own the kernel manager
  549. # and keep it alive if we don't
  550. cleanup_kc = kwargs.pop("cleanup_kc", self.owns_km)
  551. if self.km is None:
  552. self.km = self.create_kernel_manager()
  553. # self._cleanup_kernel uses run_async, which ensures the ioloop is running again.
  554. # This is necessary as the ioloop has stopped once atexit fires.
  555. atexit.register(self._cleanup_kernel)
  556. def on_signal() -> None:
  557. """Handle signals."""
  558. self._async_cleanup_kernel_future = asyncio.ensure_future(self._async_cleanup_kernel())
  559. atexit.unregister(self._cleanup_kernel)
  560. loop = asyncio.get_event_loop()
  561. try:
  562. loop.add_signal_handler(signal.SIGINT, on_signal)
  563. loop.add_signal_handler(signal.SIGTERM, on_signal)
  564. except RuntimeError:
  565. # NotImplementedError: Windows does not support signals.
  566. # RuntimeError: Raised when add_signal_handler is called outside the main thread
  567. pass
  568. if not self.km.has_kernel:
  569. await self.async_start_new_kernel(**kwargs)
  570. if self.kc is None:
  571. await self.async_start_new_kernel_client()
  572. try:
  573. yield
  574. except RuntimeError as e:
  575. await run_hook(self.on_notebook_error, notebook=self.nb)
  576. raise e
  577. finally:
  578. if cleanup_kc:
  579. await self._async_cleanup_kernel()
  580. await run_hook(self.on_notebook_complete, notebook=self.nb)
  581. atexit.unregister(self._cleanup_kernel)
  582. try:
  583. loop.remove_signal_handler(signal.SIGINT)
  584. loop.remove_signal_handler(signal.SIGTERM)
  585. except RuntimeError:
  586. pass
  587. async def async_execute(self, reset_kc: bool = False, **kwargs: t.Any) -> NotebookNode:
  588. """
  589. Executes each code cell.
  590. Parameters
  591. ----------
  592. kwargs :
  593. Any option for ``self.kernel_manager_class.start_kernel()``. Because
  594. that defaults to AsyncKernelManager, this will likely include options
  595. accepted by ``jupyter_client.AsyncKernelManager.start_kernel()``,
  596. which includes ``cwd``.
  597. ``reset_kc`` if True, the kernel client will be reset and a new one
  598. will be created (default: False).
  599. Returns
  600. -------
  601. nb : NotebookNode
  602. The executed notebook.
  603. """
  604. if reset_kc and self.owns_km:
  605. await self._async_cleanup_kernel()
  606. self.reset_execution_trackers()
  607. async with self.async_setup_kernel(**kwargs):
  608. assert self.kc is not None
  609. self.log.info("Executing notebook with kernel: %s" % self.kernel_name)
  610. msg_id = await ensure_async(self.kc.kernel_info())
  611. info_msg = await self.async_wait_for_reply(msg_id)
  612. if info_msg is not None:
  613. if "language_info" in info_msg["content"]:
  614. self.nb.metadata["language_info"] = info_msg["content"]["language_info"]
  615. else:
  616. raise RuntimeError(
  617. 'Kernel info received message content has no "language_info" key. '
  618. "Content is:\n" + str(info_msg["content"])
  619. )
  620. for index, cell in enumerate(self.nb.cells):
  621. # Ignore `'execution_count' in content` as it's always 1
  622. # when store_history is False
  623. await self.async_execute_cell(
  624. cell, index, execution_count=self.code_cells_executed + 1
  625. )
  626. self.set_widgets_metadata()
  627. return self.nb
  628. execute = run_sync(async_execute)
  629. def set_widgets_metadata(self) -> None:
  630. """Set with widget metadata."""
  631. if self.widget_state:
  632. self.nb.metadata.widgets = {
  633. "application/vnd.jupyter.widget-state+json": {
  634. "state": {
  635. model_id: self._serialize_widget_state(state)
  636. for model_id, state in self.widget_state.items()
  637. if "_model_name" in state
  638. },
  639. "version_major": 2,
  640. "version_minor": 0,
  641. }
  642. }
  643. for key, widget in self.nb.metadata.widgets[
  644. "application/vnd.jupyter.widget-state+json"
  645. ]["state"].items():
  646. buffers = self.widget_buffers.get(key)
  647. if buffers:
  648. widget["buffers"] = list(buffers.values())
  649. def _update_display_id(self, display_id: str, msg: dict[str, t.Any]) -> None:
  650. """Update outputs with a given display_id"""
  651. if display_id not in self._display_id_map:
  652. self.log.debug("display id %r not in %s", display_id, self._display_id_map)
  653. return
  654. if msg["header"]["msg_type"] == "update_display_data":
  655. msg["header"]["msg_type"] = "display_data"
  656. try:
  657. out = output_from_msg(msg)
  658. except ValueError:
  659. self.log.error(f"unhandled iopub msg: {msg['msg_type']}")
  660. return
  661. for cell_idx, output_indices in self._display_id_map[display_id].items():
  662. cell = self.nb["cells"][cell_idx]
  663. outputs = cell["outputs"]
  664. for output_idx in output_indices:
  665. outputs[output_idx]["data"] = out["data"]
  666. outputs[output_idx]["metadata"] = out["metadata"]
  667. async def _async_poll_for_reply(
  668. self,
  669. msg_id: str,
  670. cell: NotebookNode,
  671. timeout: int | None,
  672. task_poll_output_msg: asyncio.Future[t.Any],
  673. task_poll_kernel_alive: asyncio.Future[t.Any],
  674. ) -> dict[str, t.Any]:
  675. msg: dict[str, t.Any]
  676. assert self.kc is not None
  677. new_timeout: float | None = None
  678. if timeout is not None:
  679. deadline = monotonic() + timeout
  680. new_timeout = float(timeout)
  681. error_on_timeout_execute_reply = None
  682. while True:
  683. try:
  684. if error_on_timeout_execute_reply:
  685. msg = error_on_timeout_execute_reply
  686. msg["parent_header"] = {"msg_id": msg_id}
  687. else:
  688. msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))
  689. if msg["parent_header"].get("msg_id") == msg_id:
  690. if self.record_timing:
  691. cell["metadata"]["execution"]["shell.execute_reply"] = timestamp(msg)
  692. try:
  693. await asyncio.wait_for(task_poll_output_msg, self.iopub_timeout)
  694. except (asyncio.TimeoutError, Empty):
  695. if self.raise_on_iopub_timeout:
  696. task_poll_kernel_alive.cancel()
  697. raise CellTimeoutError.error_from_timeout_and_cell(
  698. "Timeout waiting for IOPub output", self.iopub_timeout, cell
  699. ) from None
  700. else:
  701. self.log.warning("Timeout waiting for IOPub output")
  702. task_poll_kernel_alive.cancel()
  703. return msg
  704. else:
  705. if new_timeout is not None:
  706. new_timeout = max(0, deadline - monotonic())
  707. except Empty:
  708. # received no message, check if kernel is still alive
  709. assert timeout is not None
  710. task_poll_kernel_alive.cancel()
  711. await self._async_check_alive()
  712. error_on_timeout_execute_reply = await self._async_handle_timeout(timeout, cell)
  713. async def _async_poll_output_msg(
  714. self, parent_msg_id: str, cell: NotebookNode, cell_index: int
  715. ) -> None:
  716. assert self.kc is not None
  717. while True:
  718. msg = await ensure_async(self.kc.iopub_channel.get_msg(timeout=None))
  719. if msg["parent_header"].get("msg_id") == parent_msg_id:
  720. try:
  721. # Will raise CellExecutionComplete when completed
  722. self.process_message(msg, cell, cell_index)
  723. except CellExecutionComplete:
  724. return
  725. async def _async_poll_kernel_alive(self) -> None:
  726. while True:
  727. await asyncio.sleep(1)
  728. try:
  729. await self._async_check_alive()
  730. except DeadKernelError:
  731. assert self.task_poll_for_reply is not None
  732. self.task_poll_for_reply.cancel()
  733. return
  734. def _get_timeout(self, cell: NotebookNode | None) -> int | None:
  735. if self.timeout_func is not None and cell is not None:
  736. timeout = self.timeout_func(cell)
  737. else:
  738. timeout = self.timeout
  739. if not timeout or timeout < 0:
  740. timeout = None
  741. return timeout
  742. async def _async_handle_timeout(
  743. self, timeout: int, cell: NotebookNode | None = None
  744. ) -> None | dict[str, t.Any]:
  745. self.log.error("Timeout waiting for execute reply (%is)." % timeout)
  746. if self.interrupt_on_timeout:
  747. self.log.error("Interrupting kernel")
  748. assert self.km is not None
  749. await ensure_async(self.km.interrupt_kernel())
  750. if self.error_on_timeout:
  751. execute_reply = {"content": {**self.error_on_timeout, "status": "error"}}
  752. return execute_reply
  753. return None
  754. else:
  755. assert cell is not None
  756. raise CellTimeoutError.error_from_timeout_and_cell(
  757. "Cell execution timed out", timeout, cell
  758. )
  759. async def _async_check_alive(self) -> None:
  760. assert self.kc is not None
  761. if not await ensure_async(self.kc.is_alive()): # type:ignore[attr-defined]
  762. self.log.error("Kernel died while waiting for execute reply.")
  763. raise DeadKernelError("Kernel died")
  764. async def async_wait_for_reply(
  765. self, msg_id: str, cell: NotebookNode | None = None
  766. ) -> dict[str, t.Any] | None:
  767. """Wait for a message reply."""
  768. assert self.kc is not None
  769. # wait for finish, with timeout
  770. timeout = self._get_timeout(cell)
  771. cummulative_time = 0
  772. while True:
  773. try:
  774. msg: dict[str, t.Any] = await ensure_async(
  775. self.kc.shell_channel.get_msg(timeout=self.shell_timeout_interval)
  776. )
  777. except Empty:
  778. await self._async_check_alive()
  779. cummulative_time += self.shell_timeout_interval
  780. if timeout and cummulative_time > timeout:
  781. await self._async_handle_timeout(timeout, cell)
  782. break
  783. else:
  784. if msg["parent_header"].get("msg_id") == msg_id:
  785. return msg
  786. return None
  787. wait_for_reply = run_sync(async_wait_for_reply)
  788. # Backwards compatibility naming for papermill
  789. _wait_for_reply = wait_for_reply
  790. def _passed_deadline(self, deadline: int | None) -> bool:
  791. if deadline is not None and deadline - monotonic() <= 0:
  792. return True
  793. return False
  794. async def _check_raise_for_error(
  795. self, cell: NotebookNode, cell_index: int, exec_reply: dict[str, t.Any] | None
  796. ) -> None:
  797. if exec_reply is None:
  798. return None
  799. exec_reply_content = exec_reply["content"]
  800. if exec_reply_content["status"] != "error":
  801. return None
  802. cell_allows_errors = (not self.force_raise_errors) and (
  803. self.allow_errors
  804. or exec_reply_content.get("ename") in self.allow_error_names
  805. or "raises-exception" in cell.metadata.get("tags", [])
  806. )
  807. await run_hook(
  808. self.on_cell_error, cell=cell, cell_index=cell_index, execute_reply=exec_reply
  809. )
  810. if not cell_allows_errors:
  811. raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
  812. async def async_execute_cell(
  813. self,
  814. cell: NotebookNode,
  815. cell_index: int,
  816. execution_count: int | None = None,
  817. store_history: bool = True,
  818. ) -> NotebookNode:
  819. """
  820. Executes a single code cell.
  821. To execute all cells see :meth:`execute`.
  822. Parameters
  823. ----------
  824. cell : nbformat.NotebookNode
  825. The cell which is currently being processed.
  826. cell_index : int
  827. The position of the cell within the notebook object.
  828. execution_count : int
  829. The execution count to be assigned to the cell (default: Use kernel response)
  830. store_history : bool
  831. Determines if history should be stored in the kernel (default: False).
  832. Specific to ipython kernels, which can store command histories.
  833. Returns
  834. -------
  835. output : dict
  836. The execution output payload (or None for no output).
  837. Raises
  838. ------
  839. CellExecutionError
  840. If execution failed and should raise an exception, this will be raised
  841. with defaults about the failure.
  842. Returns
  843. -------
  844. cell : NotebookNode
  845. The cell which was just processed.
  846. """
  847. assert self.kc is not None
  848. await run_hook(self.on_cell_start, cell=cell, cell_index=cell_index)
  849. if cell.cell_type != "code" or not cell.source.strip():
  850. self.log.debug("Skipping non-executing cell %s", cell_index)
  851. return cell
  852. if self.skip_cells_with_tag in cell.metadata.get("tags", []):
  853. self.log.debug("Skipping tagged cell %s", cell_index)
  854. return cell
  855. if self.record_timing: # clear execution metadata prior to execution
  856. cell["metadata"]["execution"] = {}
  857. self.log.debug("Executing cell:\n%s", cell.source)
  858. cell_allows_errors = (not self.force_raise_errors) and (
  859. self.allow_errors or "raises-exception" in cell.metadata.get("tags", [])
  860. )
  861. await run_hook(self.on_cell_execute, cell=cell, cell_index=cell_index)
  862. parent_msg_id = await ensure_async(
  863. self.kc.execute(
  864. cell.source, store_history=store_history, stop_on_error=not cell_allows_errors
  865. )
  866. )
  867. await run_hook(self.on_cell_complete, cell=cell, cell_index=cell_index)
  868. # We launched a code cell to execute
  869. self.code_cells_executed += 1
  870. exec_timeout = self._get_timeout(cell)
  871. cell.outputs = []
  872. self.clear_before_next_output = False
  873. task_poll_kernel_alive = asyncio.ensure_future(self._async_poll_kernel_alive())
  874. task_poll_output_msg = asyncio.ensure_future(
  875. self._async_poll_output_msg(parent_msg_id, cell, cell_index)
  876. )
  877. self.task_poll_for_reply = asyncio.ensure_future(
  878. self._async_poll_for_reply(
  879. parent_msg_id, cell, exec_timeout, task_poll_output_msg, task_poll_kernel_alive
  880. )
  881. )
  882. try:
  883. exec_reply = await self.task_poll_for_reply
  884. except asyncio.CancelledError:
  885. # can only be cancelled by task_poll_kernel_alive when the kernel is dead
  886. task_poll_output_msg.cancel()
  887. raise DeadKernelError("Kernel died") from None
  888. except Exception as e:
  889. # Best effort to cancel request if it hasn't been resolved
  890. try:
  891. # Check if the task_poll_output is doing the raising for us
  892. if not isinstance(e, CellControlSignal):
  893. task_poll_output_msg.cancel()
  894. finally:
  895. raise
  896. if execution_count:
  897. cell["execution_count"] = execution_count
  898. await run_hook(
  899. self.on_cell_executed, cell=cell, cell_index=cell_index, execute_reply=exec_reply
  900. )
  901. if self.coalesce_streams and cell.outputs:
  902. new_outputs = []
  903. streams: dict[str, NotebookNode] = {}
  904. for output in cell.outputs:
  905. if output["output_type"] == "stream":
  906. if output["name"] in streams:
  907. streams[output["name"]]["text"] += output["text"]
  908. else:
  909. new_outputs.append(output)
  910. streams[output["name"]] = output
  911. else:
  912. new_outputs.append(output)
  913. # process \r and \b characters
  914. for output in streams.values():
  915. old = output["text"]
  916. while len(output["text"]) < len(old):
  917. old = output["text"]
  918. # Cancel out anything-but-newline followed by backspace
  919. output["text"] = _RGX_BACKSPACE.sub("", output["text"])
  920. # Replace all carriage returns not followed by newline
  921. output["text"] = _RGX_CARRIAGERETURN.sub("", output["text"])
  922. # We also want to ensure stdout and stderr are always in the same consecutive order,
  923. # because they are asynchronous, so order isn't guaranteed.
  924. for i, output in enumerate(new_outputs):
  925. if output["output_type"] == "stream" and output["name"] == "stderr":
  926. if (
  927. len(new_outputs) >= i + 2
  928. and new_outputs[i + 1]["output_type"] == "stream"
  929. and new_outputs[i + 1]["name"] == "stdout"
  930. ):
  931. stdout = new_outputs.pop(i + 1)
  932. new_outputs.insert(i, stdout)
  933. cell.outputs = new_outputs
  934. await self._check_raise_for_error(cell, cell_index, exec_reply)
  935. self.nb["cells"][cell_index] = cell
  936. return cell
  937. execute_cell = run_sync(async_execute_cell)
  938. def process_message(
  939. self, msg: dict[str, t.Any], cell: NotebookNode, cell_index: int
  940. ) -> NotebookNode | None:
  941. """
  942. Processes a kernel message, updates cell state, and returns the
  943. resulting output object that was appended to cell.outputs.
  944. The input argument *cell* is modified in-place.
  945. Parameters
  946. ----------
  947. msg : dict
  948. The kernel message being processed.
  949. cell : nbformat.NotebookNode
  950. The cell which is currently being processed.
  951. cell_index : int
  952. The position of the cell within the notebook object.
  953. Returns
  954. -------
  955. output : NotebookNode
  956. The execution output payload (or None for no output).
  957. Raises
  958. ------
  959. CellExecutionComplete
  960. Once a message arrives which indicates computation completeness.
  961. """
  962. msg_type = msg["msg_type"]
  963. self.log.debug("msg_type: %s", msg_type)
  964. content = msg["content"]
  965. self.log.debug("content: %s", content)
  966. # while it's tempting to go for a more concise
  967. # display_id = content.get("transient", {}).get("display_id", None)
  968. # this breaks if transient is explicitly set to None
  969. transient = content.get("transient")
  970. display_id = transient.get("display_id") if transient else None
  971. if display_id and msg_type in {"execute_result", "display_data", "update_display_data"}:
  972. self._update_display_id(display_id, msg)
  973. # set the prompt number for the input and the output
  974. if "execution_count" in content:
  975. cell["execution_count"] = content["execution_count"]
  976. if self.record_timing:
  977. if msg_type == "status":
  978. if content["execution_state"] == "idle":
  979. cell["metadata"]["execution"]["iopub.status.idle"] = timestamp(msg)
  980. elif content["execution_state"] == "busy":
  981. cell["metadata"]["execution"]["iopub.status.busy"] = timestamp(msg)
  982. elif msg_type == "execute_input":
  983. cell["metadata"]["execution"]["iopub.execute_input"] = timestamp(msg)
  984. if msg_type == "status":
  985. if content["execution_state"] == "idle":
  986. raise CellExecutionComplete()
  987. elif msg_type == "clear_output":
  988. self.clear_output(cell.outputs, msg, cell_index)
  989. elif msg_type.startswith("comm"):
  990. self.handle_comm_msg(cell.outputs, msg, cell_index)
  991. # Check for remaining messages we don't process
  992. elif msg_type not in ["execute_input", "update_display_data"]:
  993. # Assign output as our processed "result"
  994. return self.output(cell.outputs, msg, display_id, cell_index)
  995. return None
  996. def output(
  997. self,
  998. outs: list[NotebookNode],
  999. msg: dict[str, t.Any],
  1000. display_id: str | None,
  1001. cell_index: int,
  1002. ) -> NotebookNode | None:
  1003. """Handle output."""
  1004. msg_type = msg["msg_type"]
  1005. out: NotebookNode | None = None
  1006. parent_msg_id = msg["parent_header"].get("msg_id")
  1007. if self.output_hook_stack[parent_msg_id]:
  1008. # if we have a hook registered, it will override our
  1009. # default output behaviour (e.g. OutputWidget)
  1010. hook = self.output_hook_stack[parent_msg_id][-1]
  1011. hook.output(outs, msg, display_id, cell_index)
  1012. return None
  1013. try:
  1014. out = output_from_msg(msg)
  1015. except ValueError:
  1016. self.log.error(f"unhandled iopub msg: {msg_type}")
  1017. return None
  1018. if self.clear_before_next_output:
  1019. self.log.debug("Executing delayed clear_output")
  1020. outs[:] = []
  1021. self.clear_display_id_mapping(cell_index)
  1022. self.clear_before_next_output = False
  1023. if display_id:
  1024. # record output index in:
  1025. # _display_id_map[display_id][cell_idx]
  1026. cell_map = self._display_id_map.setdefault(display_id, {})
  1027. output_idx_list = cell_map.setdefault(cell_index, [])
  1028. output_idx_list.append(len(outs))
  1029. if out:
  1030. outs.append(out)
  1031. return out
  1032. def clear_output(
  1033. self, outs: list[NotebookNode], msg: dict[str, t.Any], cell_index: int
  1034. ) -> None:
  1035. """Clear output."""
  1036. content = msg["content"]
  1037. parent_msg_id = msg["parent_header"].get("msg_id")
  1038. if self.output_hook_stack[parent_msg_id]:
  1039. # if we have a hook registered, it will override our
  1040. # default clear_output behaviour (e.g. OutputWidget)
  1041. hook = self.output_hook_stack[parent_msg_id][-1]
  1042. hook.clear_output(outs, msg, cell_index)
  1043. return
  1044. if content.get("wait"):
  1045. self.log.debug("Wait to clear output")
  1046. self.clear_before_next_output = True
  1047. else:
  1048. self.log.debug("Immediate clear output")
  1049. outs[:] = []
  1050. self.clear_display_id_mapping(cell_index)
  1051. def clear_display_id_mapping(self, cell_index: int) -> None:
  1052. """Clear a display id mapping for a cell."""
  1053. for _, cell_map in self._display_id_map.items():
  1054. if cell_index in cell_map:
  1055. cell_map[cell_index] = []
  1056. def handle_comm_msg(
  1057. self, outs: list[NotebookNode], msg: dict[str, t.Any], cell_index: int
  1058. ) -> None:
  1059. """Handle a comm message."""
  1060. content = msg["content"]
  1061. data = content["data"]
  1062. if self.store_widget_state and "state" in data: # ignore custom msg'es
  1063. self.widget_state.setdefault(content["comm_id"], {}).update(data["state"])
  1064. if data.get("buffer_paths"):
  1065. comm_id = content["comm_id"]
  1066. if comm_id not in self.widget_buffers:
  1067. self.widget_buffers[comm_id] = {}
  1068. # for each comm, the path uniquely identifies a buffer
  1069. new_buffers: dict[tuple[str, ...], dict[str, str]] = {
  1070. tuple(k["path"]): k for k in self._get_buffer_data(msg)
  1071. }
  1072. self.widget_buffers[comm_id].update(new_buffers)
  1073. # There are cases where we need to mimic a frontend, to get similar behaviour as
  1074. # when using the Output widget from Jupyter lab/notebook
  1075. if msg["msg_type"] == "comm_open":
  1076. target = msg["content"].get("target_name")
  1077. handler = self.comm_open_handlers.get(target)
  1078. if handler:
  1079. comm_id = msg["content"]["comm_id"]
  1080. comm_object = handler(msg)
  1081. if comm_object:
  1082. self.comm_objects[comm_id] = comm_object
  1083. else:
  1084. self.log.warning(f"No handler found for comm target {target!r}")
  1085. elif msg["msg_type"] == "comm_msg":
  1086. content = msg["content"]
  1087. comm_id = msg["content"]["comm_id"]
  1088. if comm_id in self.comm_objects:
  1089. self.comm_objects[comm_id].handle_msg(msg)
  1090. def _serialize_widget_state(self, state: dict[str, t.Any]) -> dict[str, t.Any]:
  1091. """Serialize a widget state, following format in @jupyter-widgets/schema."""
  1092. return {
  1093. "model_name": state.get("_model_name"),
  1094. "model_module": state.get("_model_module"),
  1095. "model_module_version": state.get("_model_module_version"),
  1096. "state": state,
  1097. }
  1098. def _get_buffer_data(self, msg: dict[str, t.Any]) -> list[dict[str, str]]:
  1099. encoded_buffers = []
  1100. paths = msg["content"]["data"]["buffer_paths"]
  1101. buffers = msg["buffers"]
  1102. for path, buffer in zip(paths, buffers, strict=False):
  1103. encoded_buffers.append(
  1104. {
  1105. "data": base64.b64encode(buffer).decode("utf-8"),
  1106. "encoding": "base64",
  1107. "path": path,
  1108. }
  1109. )
  1110. return encoded_buffers
  1111. def register_output_hook(self, msg_id: str, hook: OutputWidget) -> None:
  1112. """Registers an override object that handles output/clear_output instead.
  1113. Multiple hooks can be registered, where the last one will be used (stack based)
  1114. """
  1115. # mimics
  1116. # https://jupyterlab.github.io/jupyterlab/services/interfaces/kernel.ikernelconnection.html#registermessagehook
  1117. self.output_hook_stack[msg_id].append(hook)
  1118. def remove_output_hook(self, msg_id: str, hook: OutputWidget) -> None:
  1119. """Unregisters an override object that handles output/clear_output instead"""
  1120. # mimics
  1121. # https://jupyterlab.github.io/jupyterlab/services/interfaces/kernel.ikernelconnection.html#removemessagehook
  1122. removed_hook = self.output_hook_stack[msg_id].pop()
  1123. assert removed_hook == hook
  1124. def on_comm_open_jupyter_widget(self, msg: dict[str, t.Any]) -> t.Any | None:
  1125. """Handle a jupyter widget comm open."""
  1126. content = msg["content"]
  1127. data = content["data"]
  1128. state = data["state"]
  1129. comm_id = msg["content"]["comm_id"]
  1130. module = self.widget_registry.get(state["_model_module"])
  1131. if module:
  1132. widget_class = module.get(state["_model_name"])
  1133. if widget_class:
  1134. return widget_class(comm_id, state, self.kc, self)
  1135. return None
  1136. def execute(
  1137. nb: NotebookNode,
  1138. cwd: str | None = None,
  1139. km: KernelManager | None = None,
  1140. **kwargs: t.Any,
  1141. ) -> NotebookNode:
  1142. """Execute a notebook's code, updating outputs within the notebook object.
  1143. This is a convenient wrapper around NotebookClient. It returns the
  1144. modified notebook object.
  1145. Parameters
  1146. ----------
  1147. nb : NotebookNode
  1148. The notebook object to be executed
  1149. cwd : str, optional
  1150. If supplied, the kernel will run in this directory
  1151. km : AsyncKernelManager, optional
  1152. If supplied, the specified kernel manager will be used for code execution.
  1153. kwargs :
  1154. Any other options for NotebookClient, e.g. timeout, kernel_name
  1155. """
  1156. resources = {}
  1157. if cwd is not None:
  1158. resources["metadata"] = {"path": cwd}
  1159. return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()