Check for errors when executing initialization code (#1373)
We run some code before notebook execution to silence some warnings and set up mock backends. At the moment, errors are ignored and the kernel continues, often leading to unexpected behaviour. This PR explicitly checks for errors when running the initialization code and exits early if needed. --------- Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>
This commit is contained in:
parent
7037125c39
commit
8e505a951a
|
@ -27,7 +27,7 @@ from typing import Iterator
|
|||
import nbclient
|
||||
import nbformat
|
||||
import tomli
|
||||
from jupyter_client.manager import start_new_async_kernel
|
||||
from jupyter_client.manager import start_new_async_kernel, AsyncKernelClient
|
||||
from qiskit_ibm_runtime import QiskitRuntimeService
|
||||
from squeaky import clean_notebook
|
||||
|
||||
|
@ -226,6 +226,12 @@ async def execute_notebook(path: Path, config: Config) -> bool:
|
|||
print(f"✅ No problems in {path} (written)")
|
||||
return True
|
||||
|
||||
async def _execute_in_kernel(kernel: AsyncKernelClient, code: str) -> None:
|
||||
"""Execute code in kernel and raise if it fails"""
|
||||
response = await kernel.execute_interactive(code, store_history=False)
|
||||
if response.get("content", {}).get("status", "") == "error":
|
||||
raise Exception("Error running initialization code")
|
||||
|
||||
async def _execute_notebook(filepath: Path, config: Config) -> nbformat.NotebookNode:
|
||||
"""
|
||||
Use nbclient to execute notebook. The steps are:
|
||||
|
@ -242,9 +248,9 @@ async def _execute_notebook(filepath: Path, config: Config) -> nbformat.Notebook
|
|||
extra_arguments=["--InlineBackend.figure_format='svg'"],
|
||||
)
|
||||
|
||||
kernel.execute(PRE_EXECUTE_CODE, store_history=False)
|
||||
await _execute_in_kernel(kernel, PRE_EXECUTE_CODE)
|
||||
if config.should_patch(filepath):
|
||||
kernel.execute(MOCKING_CODE, store_history=False)
|
||||
await _execute_in_kernel(kernel, MOCKING_CODE)
|
||||
|
||||
notebook_client = nbclient.NotebookClient(
|
||||
nb=nb,
|
||||
|
|
Loading…
Reference in New Issue