### NotebookClient.start_new_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Starts a new kernel process. ```APIDOC ## NotebookClient.start_new_kernel() ### Description Starts a new kernel process. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### NotebookClient.start_new_kernel_client Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Starts a new kernel client connection. ```APIDOC ## NotebookClient.start_new_kernel_client() ### Description Starts a new kernel client connection. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Install Packaging Requirements Source: https://github.com/jupyter/nbclient/blob/main/RELEASING.md Installs necessary tools for packaging and releasing. Ensure `tomlkit` is at version 0.7.0. ```bash pip install tbump build tomlkit==0.7.0 ``` -------------------------------- ### async_start_new_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Creates a new kernel instance. Accepts options for starting the kernel, such as the working directory. ```APIDOC ## async_start_new_kernel() ### Description Creates a new kernel. ### Parameters * **kwargs**: Any options for `self.kernel_manager_class.start_kernel()`. Because that defaults to AsyncKernelManager, this will likely include options accepted by `AsyncKernelManager.start_kernel()`, which includes `cwd`. ``` -------------------------------- ### Install nbclient using pip Source: https://github.com/jupyter/nbclient/blob/main/docs/installation.md Use this command to install the nbclient package from the command line. ```bash python3 -m pip install nbclient ``` -------------------------------- ### Configure Logging to File Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/config_options.md Example of how to configure additional log handlers, specifically writing logs to a file. This merges with the base logging configuration. ```python c.Application.logging_config = { "handlers": { "file": { "class": "logging.FileHandler", "level": "DEBUG", "filename": "", } }, "loggers": { "": { "level": "DEBUG", "handlers": ["console", "file"], }, }, } ``` -------------------------------- ### NotebookClient.on_cell_start Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Callback executed before a cell starts executing. ```APIDOC ## NotebookClient.on_cell_start ### Description Callback executed before a cell starts executing. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Create and Display a Label Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/JupyterWidgets.ipynb Demonstrates how to create a simple Label widget and display it in a Jupyter environment. Requires the ipywidgets library to be installed and imported. ```python import ipywidgets label = ipywidgets.Label("Hello World") display(label) ``` -------------------------------- ### Apply Code Formatting and Linting with pre-commit Source: https://github.com/jupyter/nbclient/blob/main/CONTRIBUTING.md Use pre-commit to format and lint staged files before committing. Install it to run automatically before each commit. ```console pre-commit run ``` ```console pre-commit run --all-files ``` ```console pre-commit install ``` -------------------------------- ### Initialize Variables for Fibonacci Sequence Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Factorials.ipynb Initializes two variables, i and j, to 1. These are the starting values for the Fibonacci sequence calculation. ```python i, j = 1, 1 ``` -------------------------------- ### Format and Print Start Timestamp Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Sleep1s.ipynb Defines a time format string and prints the starting timestamp (t0) without a newline. This is often used in logging or data recording where precise timing is important. ```python time_format = "%Y-%m-%dT%H:%M:%S.%fZ" print(t0.strftime(time_format), end="") ``` -------------------------------- ### Configure Custom Logging to a File Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/config_options.md Example of how to configure nbclient to log to a file in addition to the console. This is useful for debugging or long-running processes. Ensure the application name and path to the file are correctly specified. ```python c.Application.logging_config = { "handlers": { "file": { "class": "logging.FileHandler", "level": "DEBUG", "filename": "", } }, "loggers": { "": { "level": "DEBUG", # NOTE: if you don't list the default "console" # handler here then it will be disabled "handlers": ["console", "file"], }, }, } ``` -------------------------------- ### NotebookClient.setup_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Sets up the kernel for execution. ```APIDOC ## NotebookClient.setup_kernel() ### Description Sets up the kernel for execution. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### async_setup_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Context manager for setting up the kernel to execute a notebook. It assigns the Kernel Manager and Kernel Client, and handles kernel shutdown and cleanup. ```APIDOC ## async_setup_kernel() ### Description Context manager for setting up the kernel to execute a notebook. This assigns the Kernel Manager (`self.km`) if missing and Kernel Client (`self.kc`). When control returns from the yield it stops the client’s zmq channels, and shuts down the kernel. Handlers for SIGINT and SIGTERM are also added to cleanup in case of unexpected shutdown. ### Parameters * **kwargs**: Any keyword arguments to be passed. ``` -------------------------------- ### start_new_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Creates a new kernel instance. Accepts any keyword arguments that can be passed to `AsyncKernelManager.start_kernel()`. ```APIDOC ## start_new_kernel(**kwargs) ### Description Creates a new kernel. * **Parameters:** **kwargs** – Any options for `self.kernel_manager_class.start_kernel()`. Because that defaults to AsyncKernelManager, this will likely include options accepted by `AsyncKernelManager.start_kernel()`, which includes `cwd`. ``` -------------------------------- ### NotebookClient.startup_timeout Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md The timeout duration for kernel startup. ```APIDOC ## NotebookClient.startup_timeout ### Description The timeout duration for kernel startup. ### Method This is a property or method within the NotebookClient class. ### Parameters This property/method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This property/method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### NotebookClient.on_notebook_start Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Callback executed when notebook execution begins. ```APIDOC ## NotebookClient.on_notebook_start ### Description Callback executed when notebook execution begins. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Check In-Memory History Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Check History in Memory.ipynb Get the current IPython instance and assert that its history manager is configured to use in-memory storage. ```python ip = get_ipython() assert ip.history_manager.hist_file == ":memory:" ``` -------------------------------- ### Display Help for All Options Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/config_options.md Run this command to see a comprehensive list of all available command-line options for Jupyter nbclient. ```bash $ jupyter execute --help-all ``` -------------------------------- ### start_new_kernel_client Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Creates a new kernel client instance. ```APIDOC ## start_new_kernel_client(**kwargs) ### Description Creates a new kernel client. * **Returns:** **kc** – Kernel client as created by the kernel manager `km`. * **Return type:** KernelClient ``` -------------------------------- ### start_new_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Creates a new kernel. Accepts any options for `self.kernel_manager_class.start_kernel()`, which likely includes options accepted by `AsyncKernelManager.start_kernel()`, such as `cwd`. ```APIDOC ## start_new_kernel(**kwargs: Any) -> Any ### Description Creates a new kernel. ### Parameters #### Parameters - **kwargs** (*Any*) – Any options for `self.kernel_manager_class.start_kernel()`. Because that defaults to AsyncKernelManager, this will likely include options accepted by `AsyncKernelManager.start_kernel()`, which includes `cwd`. ``` -------------------------------- ### Python ZeroDivisionError Example Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Error.ipynb This code snippet demonstrates a ZeroDivisionError, which occurs when attempting to divide by zero in Python. Ensure that all division operations have non-zero denominators to prevent this error. ```python 0 / 0 ``` -------------------------------- ### setup_kernel Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Context manager for setting up the kernel to execute a notebook. It assigns the Kernel Manager (`self.km`) if missing and Kernel Client (`self.kc`). When control returns from the yield it stops the client’s zmq channels, and shuts down the kernel. ```APIDOC ## setup_kernel(**kwargs: Any) -> Generator[None, None, None] ### Description Context manager for setting up the kernel to execute a notebook. The assigns the Kernel Manager (`self.km`) if missing and Kernel Client(`self.kc`). When control returns from the yield it stops the client’s zmq channels, and shuts down the kernel. ### Parameters #### Parameters - **kwargs** (*Any*) – Additional keyword arguments for kernel setup. ``` -------------------------------- ### Format and Print End Timestamp Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Sleep1s.ipynb Prints the ending timestamp (t1) using the same format as the start timestamp, without a newline. This allows for easy comparison of timestamps when measuring durations. ```python print(t1.strftime(time_format), end="") ``` -------------------------------- ### start_new_kernel_client Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Creates a new kernel client using the kernel manager (`km`). ```APIDOC ## start_new_kernel_client(**kwargs: Any) -> Any ### Description Creates a new kernel client. ### Returns #### Returns - **kc** – Kernel client as created by the kernel manager `km`. - **Return type:** KernelClient ### Parameters #### Parameters - **kwargs** (*Any*) – Additional keyword arguments for creating the kernel client. ``` -------------------------------- ### async_start_new_kernel_client Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Creates and returns a new kernel client associated with the kernel manager. ```APIDOC ## async_start_new_kernel_client() ### Description Creates a new kernel client. ### Returns * **kc** (KernelClient): Kernel client as created by the kernel manager `km`. ``` -------------------------------- ### Execute Notebook Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md Run the configured notebook. Outputs will be populated after execution. ```default client.execute() ``` -------------------------------- ### Initial Display and Update with display_with_id Source: https://github.com/jupyter/nbclient/blob/main/tests/files/update-display-id.ipynb Demonstrates the initial display of content and subsequent updates using the `display_with_id` function. Note how 'here' is updated, while 'above' and 'below' are distinct initial displays. ```python display("above") display_with_id(1, "here") display("below") ``` -------------------------------- ### Build and Upload to PyPI Source: https://github.com/jupyter/nbclient/blob/main/RELEASING.md Cleans previous build artifacts, builds the project distribution, and uploads it to PyPI using `twine`. ```bash rm -rf dist/* rm -rf build/* python -m build . twine upload dist/* ``` -------------------------------- ### Create and Display a Third Output Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Initializes a third `ipywidgets.Output` widget for demonstrating sequential output updates. ```python import ipywidgets as widgets output3 = widgets.Output() output3 ``` -------------------------------- ### Create and Display an Output Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Initializes an `ipywidgets.Output` widget. This widget will capture and display output directed to it. ```python import ipywidgets as widgets from IPython.display import clear_output output1 = widgets.Output() output1 ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter/nbclient/blob/main/binder/run_nbclient.ipynb Import nbformat for notebook manipulation, pandas for data handling, scrapbook for saving/loading notebook outputs, and nbclient for notebook execution. ```python import nbformat as nbf import pandas as pd import scrapbook as sb import nbclient ``` -------------------------------- ### Import nbformat and NotebookClient Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md Import necessary libraries for notebook manipulation and execution. ```default import nbformat from nbclient import NotebookClient ``` -------------------------------- ### Configure Notebook Execution Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md Instantiate NotebookClient with the notebook object and optional execution parameters. The 'path' in resources specifies the directory for execution. ```default client = NotebookClient(nb, timeout=600, kernel_name='python3', resources={'metadata': {'path': 'notebooks/'}}) ``` -------------------------------- ### Create and Display a Second Output Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Initializes another `ipywidgets.Output` widget, similar to the first, for separate output management. ```python import ipywidgets as widgets output2 = widgets.Output() output2 ``` -------------------------------- ### Create and Display a Fifth Output Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Initializes a fifth `ipywidgets.Output` widget for demonstrating the display of rich output and subsequent clearing. ```python import ipywidgets as widgets output5 = widgets.Output() output5 ``` -------------------------------- ### Import clear_output Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Clear Output.ipynb Import the necessary function from IPython.display. ```python from IPython.display import clear_output ``` -------------------------------- ### Create a Comm Instance Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Other Comms.ipynb Create a new comm instance with a specified target name and initial data. This is useful for establishing a communication channel. ```python comm = create_comm("this-comm-tests-a-missing-handler", data={"id": "foo"}) ``` -------------------------------- ### execute Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Executes all code cells in a notebook. Accepts options for kernel startup and client reset. ```APIDOC ## execute(**kwargs: Any) ### Description Executes each code cell. ### Parameters * **kwargs**: Any option for `self.kernel_manager_class.start_kernel()`. Because that defaults to AsyncKernelManager, this will likely include options accepted by `jupyter_client.AsyncKernelManager.start_kernel()`, which includes `cwd`. `reset_kc` if True, the kernel client will be reset and a new one will be created (default: False). ### Returns * **nb** (NotebookNode): The executed notebook. * **Return type**: NotebookNode ``` -------------------------------- ### Sequential Output Update with Clear Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Shows how to print initial text, clear it, and then print new text within `output3`. `clear_output()` without `wait=True` immediately removes previous content. ```python print("hi3") with output3: print("hello") clear_output(wait=True) print("world") ``` -------------------------------- ### execute() Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Executes a notebook. ```APIDOC ## execute() ### Description Executes a notebook. ### Method This is a function within the nbclient module. ### Parameters This function does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This function does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Display an Image File Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Inline Image.ipynb Instantiate the Image class with a filename to display the image inline. Ensure the image file exists in the same directory or provide a valid path. ```python Image("python.png") ``` -------------------------------- ### Read and execute a notebook with nbclient Source: https://github.com/jupyter/nbclient/blob/main/binder/run_nbclient.ipynb Use nbformat to read a notebook file into memory and then nbclient.execute to run the notebook's cells. The executed notebook object, now containing outputs, is returned. ```python # We use nbformat to represent our empty notebook in-memory b = nbf.read("./empty_notebook.ipynb", nbf.NO_CONVERT) # Execute our in-memory notebook, which will now have outputs b = nbclient.execute(nb) ``` -------------------------------- ### Generate API Documentation with Sphinx Source: https://github.com/jupyter/nbclient/blob/main/docs/UPDATE.md Use this command to generate API documentation from your Python code. The -f flag overwrites existing files. Specify the output directory and the source directory for your code. ```bash sphinx-apidoc -f -o reference ../nbclient ``` -------------------------------- ### Display Help for jupyter execute Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md View all available options and configurations for the `jupyter execute` command. This includes options for error handling, timeouts, and kernel selection. ```bash jupyter execute --help ``` -------------------------------- ### Run All Tests with hatch Source: https://github.com/jupyter/nbclient/blob/main/CONTRIBUTING.md Execute all project tests using the hatch build tool. This command ensures the test environment and dependencies are managed automatically. ```console hatch run test:test ``` -------------------------------- ### Load a Notebook Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md Load a notebook file using nbformat. Ensure the notebook_filename variable contains the correct path. ```default nb = nbformat.read(notebook_filename, as_version=4) ``` -------------------------------- ### NotebookClient Methods Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md This section details the methods available on the NotebookClient class for managing notebook execution, kernel interactions, and error handling. ```APIDOC ## NotebookClient.shutdown_kernel ### Description Shuts down the kernel associated with the NotebookClient. ### Method `shutdown_kernel()` ### Endpoint N/A (Method call) ### Parameters None ### Request Example ```python client.shutdown_kernel() ``` ### Response None ``` ```APIDOC ## NotebookClient.skip_cells_with_tag ### Description Configures the client to skip cells that have a specific tag. ### Method `skip_cells_with_tag(tag)` ### Parameters * **tag** (str) - The tag to identify cells to be skipped. ### Request Example ```python client.skip_cells_with_tag('skip-execution') ``` ``` ```APIDOC ## NotebookClient.start_new_kernel ### Description Starts a new kernel for the NotebookClient. ### Method `start_new_kernel()` ### Request Example ```python client.start_new_kernel() ``` ``` ```APIDOC ## NotebookClient.start_new_kernel_client ### Description Starts a new kernel client for the NotebookClient. ### Method `start_new_kernel_client()` ### Request Example ```python client.start_new_kernel_client() ``` ``` ```APIDOC ## NotebookClient.store_widget_state ### Description Stores the current state of widgets managed by the client. ### Method `store_widget_state()` ### Request Example ```python client.store_widget_state() ``` ``` ```APIDOC ## NotebookClient.wait_for_reply ### Description Waits for a reply from the kernel. ### Method `wait_for_reply()` ### Request Example ```python client.wait_for_reply() ``` ``` ```APIDOC ## execute ### Description Executes a notebook. ### Method `execute(nb, km=None, **kwargs)` ### Parameters * **nb** (NotebookNode) - The notebook object to execute. * **km** (KernelManager, optional) - An existing kernel manager to use. * **kwargs** - Additional keyword arguments to pass to the execution process. ### Request Example ```python from nbclient import execute execute(notebook_object) ``` ``` ```APIDOC ## timestamp ### Description Returns the current timestamp. ### Method `timestamp()` ### Request Example ```python from nbclient import timestamp timestamp() ``` ``` ```APIDOC ## NotebookClient.async_execute ### Description Asynchronously executes a notebook. ### Method `async_execute(nb, km=None, **kwargs)` ### Parameters * **nb** (NotebookNode) - The notebook object to execute. * **km** (KernelManager, optional) - An existing kernel manager to use. * **kwargs** - Additional keyword arguments to pass to the execution process. ### Request Example ```python await client.async_execute(notebook_object) ``` ``` ```APIDOC ## NotebookClient.async_execute_cell ### Description Asynchronously executes a single cell within a notebook. ### Method `async_execute_cell(cell, store_history=True, **kwargs)` ### Parameters * **cell** (Cell) - The cell object to execute. * **store_history** (bool, optional) - Whether to store the cell execution in history. Defaults to True. * **kwargs** - Additional keyword arguments to pass to the execution process. ### Request Example ```python await client.async_execute_cell(cell_object) ``` ``` ```APIDOC ## NotebookClient.async_setup_kernel ### Description Asynchronously sets up the kernel for execution. ### Method `async_setup_kernel(kernel_name='python3', **kwargs)` ### Parameters * **kernel_name** (str, optional) - The name of the kernel to set up. Defaults to 'python3'. * **kwargs** - Additional keyword arguments for kernel setup. ### Request Example ```python await client.async_setup_kernel() ``` ``` ```APIDOC ## NotebookClient.async_start_new_kernel ### Description Asynchronously starts a new kernel. ### Method `async_start_new_kernel(**kwargs)` ### Parameters * **kwargs** - Additional keyword arguments for starting the kernel. ### Request Example ```python await client.async_start_new_kernel() ``` ``` ```APIDOC ## NotebookClient.async_start_new_kernel_client ### Description Asynchronously starts a new kernel client. ### Method `async_start_new_kernel_client(**kwargs)` ### Parameters * **kwargs** - Additional keyword arguments for starting the kernel client. ### Request Example ```python await client.async_start_new_kernel_client() ``` ``` ```APIDOC ## NotebookClient.async_wait_for_reply ### Description Asynchronously waits for a reply from the kernel. ### Method `async_wait_for_reply(**kwargs)` ### Parameters * **kwargs** - Additional keyword arguments for waiting. ### Request Example ```python await client.async_wait_for_reply() ``` ``` ```APIDOC ## NotebookClient.clear_display_id_mapping ### Description Clears the mapping of display IDs. ### Method `clear_display_id_mapping()` ### Request Example ```python client.clear_display_id_mapping() ``` ``` ```APIDOC ## NotebookClient.clear_output ### Description Clears the output of cells. ### Method `clear_output(output_types=None)` ### Parameters * **output_types** (list, optional) - A list of output types to clear. If None, all outputs are cleared. ### Request Example ```python client.clear_output(output_types=['execute_result']) ``` ``` ```APIDOC ## NotebookClient.coalesce_streams ### Description Coalesces output streams. ### Method `coalesce_streams(cell)` ### Parameters * **cell** (Cell) - The cell whose output streams are to be coalesced. ### Request Example ```python client.coalesce_streams(cell_object) ``` ``` ```APIDOC ## NotebookClient.create_kernel_manager ### Description Creates a kernel manager instance. ### Method `create_kernel_manager(**kwargs)` ### Parameters * **kwargs** - Additional keyword arguments for creating the kernel manager. ### Request Example ```python client.create_kernel_manager() ``` ``` ```APIDOC ## NotebookClient.execute ### Description Executes a notebook. ### Method `execute(nb, km=None, **kwargs)` ### Parameters * **nb** (NotebookNode) - The notebook object to execute. * **km** (KernelManager, optional) - An existing kernel manager to use. * **kwargs** - Additional keyword arguments to pass to the execution process. ### Request Example ```python client.execute(notebook_object) ``` ``` ```APIDOC ## NotebookClient.execute_cell ### Description Executes a single cell within a notebook. ### Method `execute_cell(cell, store_history=True, **kwargs)` ### Parameters * **cell** (Cell) - The cell object to execute. * **store_history** (bool, optional) - Whether to store the cell execution in history. Defaults to True. * **kwargs** - Additional keyword arguments to pass to the execution process. ### Request Example ```python client.execute_cell(cell_object) ``` ``` ```APIDOC ## NotebookClient.handle_comm_msg ### Description Handles a comm message from the kernel. ### Method `handle_comm_msg(msg)` ### Parameters * **msg** (dict) - The comm message received from the kernel. ### Request Example ```python client.handle_comm_msg(message_dict) ``` ``` ```APIDOC ## NotebookClient.interrupt_on_timeout ### Description Configures the client to interrupt the kernel if a timeout occurs during cell execution. ### Method `interrupt_on_timeout(timeout)` ### Parameters * **timeout** (float) - The timeout duration in seconds. ### Request Example ```python client.interrupt_on_timeout(60.0) ``` ``` -------------------------------- ### Import IPython Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Check History in Memory.ipynb Import the necessary IPython module to access the interactive shell. ```python from IPython import get_ipython ``` -------------------------------- ### Configuration Options Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Various configuration options that can be set to control the behavior of the notebook client during execution. ```APIDOC #### ipython_hist_file Path to file to use for SQLite history database for an IPython kernel. The specific value `:memory:` (including the colon at both end but not the back ticks), avoids creating a history file. Otherwise, IPython will create a history file for each kernel. When running kernels simultaneously (e.g. via multiprocessing) saving history a single SQLite file can result in database errors, so using `:memory:` is recommended in non-interactive contexts. #### kc *: KernelClient | None* #### kernel_manager_class The kernel manager class to use. #### kernel_name Name of kernel to use to execute the cells. If not set, use the kernel_spec embedded in the notebook. #### km *: KernelManager | None* #### nb *: NotebookNode* #### owns_km *: bool* #### raise_on_iopub_timeout If `False` (default), then the kernel will continue waiting for iopub messages until it receives a kernel idle message, or until a timeout occurs, at which point the currently executing cell will be skipped. If `True`, then an error will be raised after the first timeout. This option generally does not need to be used, but may be useful in contexts where there is the possibility of executing notebooks with memory-consuming infinite loops. #### record_timing If `True` (default), then the execution timings of each cell will be stored in the metadata of the notebook. ``` -------------------------------- ### Create a file for inter-notebook communication Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Parallel Execute A.ipynb Writes a message to a file in a temporary directory, identifying the notebook instance. This file serves as a communication channel between parallel notebook executions. ```python # the variable this_notebook is injectected in a cell above by the test framework. this_notebook = "A" other_notebook = "B" directory = os.environ["NBEXECUTE_TEST_PARALLEL_TMPDIR"] with open(os.path.join(directory, f"test_file_{this_notebook}.txt"), "w") as f: f.write(f"Hello from {this_notebook}") ``` -------------------------------- ### Import Image Class from IPython.display Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Inline Image.ipynb Import the necessary Image class for displaying images. ```python from IPython.display import Image ``` -------------------------------- ### Create and Display a Fourth Output Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Initializes a fourth `ipywidgets.Output` widget to demonstrate clearing output after displaying content. ```python import ipywidgets as widgets output4 = widgets.Output() output4 ``` -------------------------------- ### Nested Output Widgets Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Demonstrates the use of nested `Output` widgets, where output from an inner widget is captured within an outer widget's context. ```python import ipywidgets as widgets output_outer = widgets.Output() output_inner = widgets.Output() output_inner ``` ```python output_outer ``` ```python with output_inner: print("in inner") with output_outer: print("in outer") print("also in inner") ``` -------------------------------- ### Redirect Exception to Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Demonstrates how to capture exceptions raised within a `with` block and have them displayed in the `Output` widget. This is helpful for debugging. ```python with output1: raise ValueError("trigger msg_type=error") ``` -------------------------------- ### NotebookClient.on_comm_open_jupyter_widget Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Handles the opening of a Jupyter Comm channel for widgets. ```APIDOC ## NotebookClient.on_comm_open_jupyter_widget() ### Description Handles the opening of a Jupyter Comm channel for widgets. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Print Output in Python Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Skip Exceptions.ipynb A simple Python snippet to print the string 'ok' to standard output. This is commonly used for basic testing and debugging. ```python print("ok") ``` -------------------------------- ### NotebookClient.on_notebook_complete Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Callback executed when the entire notebook execution is successfully completed. ```APIDOC ## NotebookClient.on_notebook_complete ### Description Callback executed when the entire notebook execution is successfully completed. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Capture Standard Output Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Skip Exceptions with Cell Tags.ipynb This output block shows the standard output captured from the preceding Python code. It displays the 'hello' string printed to stdout. ```text hello\n ``` -------------------------------- ### Execute Code and Skip Exceptions Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Skip Exceptions with Cell Tags.ipynb This code block demonstrates basic Python execution, including printing to standard output and standard error, and raising an exception. The subsequent output sections show how the notebook handles these operations, including the captured stderr and the skipped exception. ```python import sys\nprint("hello")\nprint("errorred", file=sys.stderr)\n# üñîçø∂é\nraise Exception("message") ``` -------------------------------- ### Set New Version for Release Source: https://github.com/jupyter/nbclient/blob/main/RELEASING.md Sets the environment variable for the new version to be used in the release process. ```bash export version= ``` -------------------------------- ### NotebookClient.resources Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Provides access to resources managed by the NotebookClient. ```APIDOC ## NotebookClient.resources ### Description Provides access to resources managed by the NotebookClient. ### Method This is a property or method within the NotebookClient class. ### Parameters This property/method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This property/method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### execute Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Executes each code cell in the notebook. Accepts keyword arguments that can be passed to the kernel manager's start_kernel method, such as `cwd`. The `reset_kc` option can be used to reset the kernel client. ```APIDOC ## execute ### Description Executes each code cell. ### Parameters * **kwargs** (*Any*) – Any option for `self.kernel_manager_class.start_kernel()`. This may include options accepted by `jupyter_client.AsyncKernelManager.start_kernel()`, such as `cwd`. * **reset_kc** (*bool*) – If True, the kernel client will be reset and a new one will be created (default: False). ### Returns * **nb** (*NotebookNode*) – The executed notebook. * **Return type:** NotebookNode ``` -------------------------------- ### Display Rich Output and Clear Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Captures and displays rich output (using `display`) into `output5`, then clears it. Note that `display` is used for rich content, while `print` is for text streams. ```python print("hi5") with output5: display("hello world") # this is not a stream but plain text clear_output() ``` -------------------------------- ### Display with ID and Update Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Clear Output.ipynb Demonstrates updating an output element managed by `display_id`. The initial display might be overwritten by subsequent operations. ```python handle1 = display("Hello", display_id="id1") ``` ```python handle1.update("world") ``` -------------------------------- ### Run Tests with Coverage using hatch Source: https://github.com/jupyter/nbclient/blob/main/CONTRIBUTING.md Generate a test coverage report using hatch, which is typically used for CI processes. This command helps in assessing the thoroughness of the test suite. ```console hatch run cov:test ``` -------------------------------- ### Import create_comm Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Other Comms.ipynb Import the necessary function to create a comm object. ```python from comm import create_comm ``` -------------------------------- ### NotebookClient Class Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md The NotebookClient class provides methods for executing notebook cells, managing kernel lifecycles, and handling execution errors. ```APIDOC ## Class: nbclient.client.NotebookClient ### Description Encompasses a Client for executing cells in a notebook. ### Attributes - **allow_error_names** (list): List of error names which won’t stop the execution. Use this if the `allow_errors` option it too general and you want to allow only specific kinds of errors. - **allow_errors** (bool): If `False` (default), when a cell raises an error the execution is stopped and a `CellExecutionError` is raised, except if the error name is in `allow_error_names`. If `True`, execution errors are ignored and the execution is continued until the end of the notebook. Output from exceptions is included in the cell output in both cases. - **coalesce_streams** (bool): Merge all stream outputs with shared names into single streams. - **display_data_priority** (list): An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others. - **error_on_timeout** (dict): If a cell execution was interrupted after a timeout, don’t wait for the execute_reply from the kernel (e.g. KeyboardInterrupt error). Instead, return an execute_reply with the given error, which should be of the following form: ```default { 'ename': str, # Exception name, as a string 'evalue': str, # Exception value, as a string 'traceback': list(str), # traceback frames, as strings } ``` ### Methods #### async_execute(reset_kc: bool = False, **kwargs: Any) -> NotebookNode ##### Description Executes each code cell. ##### Parameters - **kwargs** (Any): Any option for `self.kernel_manager_class.start_kernel()`. Because that defaults to AsyncKernelManager, this will likely include options accepted by `jupyter_client.AsyncKernelManager.start_kernel()`, which includes `cwd`. - **reset_kc** (bool): If True, the kernel client will be reset and a new one will be created (default: False). ##### Returns - **nb** (NotebookNode): The executed notebook. #### async_execute_cell(cell: NotebookNode, cell_index: int, execution_count: int | None = None, store_history: bool = True) -> NotebookNode ##### Description Executes a single code cell. To execute all cells see [`execute()`](#nbclient.client.execute). ##### Parameters - **cell** (NotebookNode): The cell which is currently being processed. - **cell_index** (int): The position of the cell within the notebook object. - **execution_count** (int | None): The execution count to be assigned to the cell (default: Use kernel response). - **store_history** (bool): Determines if history should be stored in the kernel (default: False). Specific to ipython kernels, which can store command histories. ##### Returns - **cell** (NotebookNode): The cell which was just processed. ##### Raises - **CellExecutionError**: If execution failed and should raise an exception, this will be raised with defaults about the failure. #### async_setup_kernel(**kwargs: Any) -> AsyncGenerator[None, None] ##### Description Context manager for setting up the kernel to execute a notebook. This assigns the Kernel Manager (`self.km`) if missing and Kernel Client(`self.kc`). When control returns from the yield it stops the client’s zmq channels, and shuts down the kernel. Handlers for SIGINT and SIGTERM are also added to cleanup in case of unexpected shutdown. #### async_start_new_kernel(**kwargs: Any) -> None ##### Description Creates a new kernel. ##### Parameters - **kwargs** (Any): Any options for `self.kernel_manager_class.start_kernel()`. Because that defaults to AsyncKernelManager, this will likely include options accepted by `AsyncKernelManager.start_kernel()`, which includes `cwd`. #### async_start_new_kernel_client() -> KernelClient ##### Description Creates a new kernel client. ##### Returns - **kc** (KernelClient): Kernel client as created by the kernel manager `km`. #### async_wait_for_reply(msg_id: str, cell: NotebookNode | None = None) -> dict[str, Any] | None ##### Description Wait for a message reply. #### clear_display_id_mapping(cell_index: int) -> None ##### Description Clear a display id mapping for a cell. #### clear_output(outs: list[NotebookNode], msg: dict[str, Any], cell_index: int) -> None ##### Description Clear output. #### create_kernel_manager() -> KernelManager ##### Description Creates a new kernel manager. ##### Returns - **km** (KernelManager): Kernel manager whose client class is asynchronous. ``` -------------------------------- ### NotebookClient.raise_on_iopub_timeout Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Controls whether to raise an exception on IOPub timeout. ```APIDOC ## NotebookClient.raise_on_iopub_timeout ### Description Controls whether to raise an exception on IOPub timeout. ### Method This is a property or method within the NotebookClient class. ### Parameters This property/method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This property/method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Save Executed Notebook Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md Write the notebook with populated outputs to a new .ipynb file. ```default nbformat.write(nb, 'executed_notebook.ipynb') ``` -------------------------------- ### on_comm_open_jupyter_widget Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/nbclient.md Handles the opening of a Jupyter widget comm. ```APIDOC ## on_comm_open_jupyter_widget ### Description Handle a jupyter widget comm open. ### Parameters * **msg** (*dict[str, Any]*) – The comm open message dictionary. ``` -------------------------------- ### Execute Multiple Notebooks Source: https://github.com/jupyter/nbclient/blob/main/docs/client.md Execute multiple Jupyter notebooks sequentially by providing them as arguments to the `jupyter execute` command. ```bash jupyter execute notebook.ipynb notebook2.ipynb ``` -------------------------------- ### Import Matplotlib for Plotting Source: https://github.com/jupyter/nbclient/blob/main/binder/empty_notebook.ipynb Import the matplotlib library for creating visualizations. ```python import matplotlib.pyplot as plt ``` -------------------------------- ### Send Data via Comm Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Other Comms.ipynb Send data through an existing comm instance. Ensure the comm is properly initialized before sending. ```python comm.send(data={"id": "bar"}) ``` -------------------------------- ### Write to a file for inter-notebook communication Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Parallel Execute B.ipynb This code writes a message to a file in a temporary directory, identifying the notebook instance ('A' or 'B'). This file serves as a signal for other instances. ```python # the variable this_notebook is injectected in a cell above by the test framework. this_notebook = "B" other_notebook = "A" directory = os.environ["NBEXECUTE_TEST_PARALLEL_TMPDIR"] with open(os.path.join(directory, f"test_file_{this_notebook}.txt"), "w") as f: f.write(f"Hello from {this_notebook}") ``` -------------------------------- ### NotebookClient Class Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md The NotebookClient class provides methods for executing notebook cells and managing the notebook execution lifecycle. ```APIDOC ## Class: NotebookClient ### Description Provides methods for executing notebook cells and managing the notebook execution lifecycle. ### Methods - `allow_error_names` - `allow_errors` - `async_execute()` - `async_execute_cell()` - `async_setup_kernel()` - `async_start_new_kernel()` - `async_start_new_kernel_client()` - `async_wait_for_reply()` - `clear_display_id_mapping()` - `clear_output()` - `coalesce_streams` - `create_kernel_manager()` - `display_data_priority` - `error_on_timeout` - `execute()` - `execute_cell()` - `extra_arguments` - `force_raise_errors` - `handle_comm_msg()` - `interrupt_on_timeout` - `iopub_timeout` - `ipython_hist_file` - `kernel_manager_class` - `kernel_name` - `on_cell_complete` - `on_cell_error` - `on_cell_execute` - `on_cell_executed` - `on_cell_start` - `on_comm_open_jupyter_widget()` - `on_notebook_complete` - `on_notebook_error` - `on_notebook_start` - `output()` - `process_message()` - `raise_on_iopub_timeout` - `record_timing` - `register_output_hook()` - `remove_output_hook()` - `reset_execution_trackers()` - `resources` - `set_widgets_metadata()` - `setup_kernel()` - `shell_timeout_interval` ``` -------------------------------- ### NotebookClient.widget_registry Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Registry for managing Jupyter widgets. ```APIDOC ## NotebookClient.widget_registry ### Description Registry for managing Jupyter widgets. ### Method This is a property or method within the NotebookClient class. ### Parameters This property/method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This property/method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ``` -------------------------------- ### Import Libraries for Data Handling Source: https://github.com/jupyter/nbclient/blob/main/binder/empty_notebook.ipynb Import necessary libraries for data manipulation and notebook interaction. ```python import numpy as np import pandas as pd import scrapbook as sb ``` -------------------------------- ### Import necessary modules Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Parallel Execute A.ipynb Imports the 'os', 'os.path', and 'time' modules for file system operations and time-related functions. ```python import os import os.path import time ``` -------------------------------- ### Redirect Print Output to Widget Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Output.ipynb Captures standard output (like print statements) and redirects it into the specified `Output` widget. This is useful for dynamic content generation. ```python print("hi") with output1: print("in output") ``` -------------------------------- ### Basic Clear Output Source: https://github.com/jupyter/nbclient/blob/main/tests/files/Clear Output.ipynb Demonstrates clearing output after printing a message. The message will not be displayed. ```python print("Hello world") clear_output() ``` -------------------------------- ### NotebookClient.wait_for_reply Source: https://github.com/jupyter/nbclient/blob/main/docs/reference/modules.md Waits for a reply from the kernel. ```APIDOC ## NotebookClient.wait_for_reply() ### Description Waits for a reply from the kernel. ### Method This is a method within the NotebookClient class. ### Parameters This method does not explicitly list parameters in the source. Refer to the nbclient documentation for details on potential implicit parameters or context. ### Response This method does not explicitly define a return value in the source. Refer to the nbclient documentation for details on potential implicit return values or side effects. ```