0

I am planning to use Jupyter Notebooks to generate reports. Reports would be generated by running a template notebook and then converting the resulting notebook to static HTML and image assets (using nbconvert if needed).

However, I am not sure how I can control the notebook execution programmatically. I would like to pass reporting data from the host Python interpreter to the notebook executor so that any passed data would be available as global or local variables in notebook cells.

Is it possible to programmatically inject variables into the notebook execution context? There is ExecutePreprocesser example, outside running and saving the notebook, it does not really describe all options what you can do with it.

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435

1 Answers1

2

You can combine the use of Papermill to run the notebook with the parameterized variables and then use jupyter nbconvert to convert the executed notebook into your preferred format.

Alternatives to Papermill for injecting variables...

At the time I was using Papermill, I found that it would leave some boilerplate text at the top that I didn't want. Rather than stripping that out using nbformat, often I made a template in markdown with placeholders and then used string substitution from Python to replace the placeholders and then finally executed that markdown as a notebook using Jupytext, which allows making notebooks from Markdown or saving as markdown, see here.

The top of my answer here has good coverage of the use of nbformat, if that is something you are interested in for this process as it offers a way to vary and control differently. You can then use nbformat to construct the notebooks out of the elements programmatically with that as well, and then, if necessary still, do the substitution with Python, and finally run the execution with jupyter nbconvert or Jupytext.

Wayne
  • 6,607
  • 8
  • 36
  • 93