Pre-Executing Notebooks

Automatically executing notebooks during the Sphinx build process is an important feature of nbsphinx. However, there are a few use cases where pre-executing a notebook and storing the outputs might be preferable. Storing any output will, by default, stop nbsphinx from executing the notebook.

Long-Running Cells

If you are doing some very time-consuming computations, it might not be feasible to re-execute the notebook every time you build your Sphinx documentation.

So just do it once – when you happen have the time – and then just keep the output.

In [1]:
import time
In [2]:
%time time.sleep(60 * 60)
6 * 7
CPU times: user 160 ms, sys: 56 ms, total: 216 ms
Wall time: 1h 1s
Out[2]:
42

If you do want to execute your notebooks, but some cells run for a long time, you can change the timeout, see Cell Execution Timeout.

Rare Libraries

You might have created results with a library that’s hard to install and therefore you have only managed to install it on one very old computer in the basement, so you probably cannot run this whenever you build your Sphinx docs.

In [3]:
from a_very_rare_library import calculate_the_answer
In [4]:
calculate_the_answer()
Out[4]:
42

Exceptions

If an exception is raised during the Sphinx build process, it is stopped (the build process, not the exception!). If you want to show to your audience how an exception looks like, you have two choices:

  1. Allow errors – either generally or on a per-notebook basis – see Ignoring Errors.
  2. Execute the notebook beforehand and save the results, like it’s done in this example notebook:
In [5]:
1 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-b710d87c980c> in <module>()
----> 1 1 / 0

ZeroDivisionError: division by zero