{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import nbclient\n", "import nbformat as nbf\n", "import pandas as pd\n", "import scrapbook as sb" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Background\n", "\n", "This notebook uses `nbclient` to read and execute an *empty* notebook.\n", "The empty notebook generates some fake data, makes a plot, and stores\n", "both the data and the plot inside the notebook using the\n", "[scrapbook package](https://github.com/nteract/scrapbook). We will\n", "then be able to access the generated contents of the notebook here.\n", "\n", "You can see the empty notebook by clicking this button:\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Read and execute the empty notebook" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We use nbformat to represent our empty notebook in-memory\n", "nb = nbf.read('./empty_notebook.ipynb', nbf.NO_CONVERT)\n", "\n", "# Execute our in-memory notebook, which will now have outputs\n", "nb = nbclient.execute(nb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Inspect the new notebook for its contents" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First we'll convert our nbformat NotebokNote into a *scrapbook* NotebookNode\n", "nb = sb.read_notebook(nb)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We can access the dataframe that was created and glued into the empty notebook\n", "pd.DataFrame.from_dict(nb.scraps.get('dataframe').data).head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We can also access the generated plot by \"re-gluing\" the notebook here\n", "nb.reglue('plot')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }