Execute a jupyter notebook, fast, without needing jupyter
Install the lightweight shell:
pip install execnb
For the full IPython shell, including its extensions and magics:
pip install 'execnb[ipython]'
For conda, run conda install -c fastai execnb (mamba also works).
CaptureShell runs cell strings and captures notebook outputs without a notebook file or a Jupyter server. It uses IPython if installed. Otherwise it uses minipy, execnb's built-in subset of IPython. To require full IPython, pass use_ipython=True. To select minipy explicitly, create CaptureShell(use_ipython=False) before anything imports IPython. All CaptureShell instances in a process use the same backend.
After creating a lean shell, both from IPython.display import Markdown, display and from IPython import display work in cells and imported Python modules. The first imports the callable display; the second imports the module, so use display.Markdown(...) or display.display(...). This makes the display API available without installing full IPython.
Each shell runs cells on its own event loop in a background thread. Call run from a script, notebook, or async server; the cell can use top-level await:
from execnb.shell import *
from fastcore.utils import *
from fastcore.nbio import *
s = CaptureShell()
s.run('1+1')
[{'data': {'text/plain': ['2']},
'metadata': {},
'output_type': 'execute_result',
'execution_count': 1}]
To execute a notebook and save it with outputs filled in, call s.execute:
try:
s.execute('../tests/clean.ipynb', 'tmp.ipynb')
print(read_nb('tmp.ipynb').cells[1].outputs)
finally: Path('tmp.ipynb').unlink()
[{'name': 'stdout', 'output_type': 'stream', 'text': '1\n'}, {'data': {'text/plain': '2'}, 'execution_count': 3, 'metadata': {}, 'output_type': 'execute_result'}]
You can also execute notebooks from the command line with exec_nb:
!exec_nb --help
usage: exec_nb [-h] [--dest (str)] [--exc-stop] [--inject-code (str)] [--inject-path (str)] [--inject-idx (int)]
[--verbose] [--cell-timeout (int)]
src
Execute notebook from `src` and save with outputs to `dest`
positional arguments:
src Notebook path to read from
options:
-h, --help show this help message and exit
--dest (str) Notebook path to write to (default: '')
--exc-stop Stop on exceptions? (default: False)
--inject-code (str) Code to inject into a cell
--inject-path (str) Path to file containing code to inject into a cell
--inject-idx (int) Cell to replace with `inject_code` (default: 0)
--verbose Show stdout/stderr during execution (default: False)
--cell-timeout (int) Seconds before each cell times out (None: no limit)
execnb 0.3.5
Use execnb.minipy.inputtransformer2 to recognize notebook commands without installing IPython or running a shell. A linter can find the position of a command in the original source:
from execnb.minipy.inputtransformer2 import TransformerManager, TokenTransformBase, make_tokens_by_line
manager = TransformerManager()
source = 'files = !ls'
tokens = make_tokens_by_line(source.splitlines(keepends=True))
matches = [m for cls in manager.token_transformers if (m := cls.find(tokens))]
first = min(matches, key=TokenTransformBase.sortby)
first.start_line, first.start_col
(0, 8)
Line and column numbers start at zero. Each transformer finds its first match or returns None. sortby orders matches by position, then by priority. Retokenize after each edit to find the next command. To translate a whole cell to Python, including cell magics such as %%bash, use manager.transform_cell(source).