Metadata-Version: 2.4
Name: execnb
Version: 0.4.0
Summary: Execute notebook cells and capture their outputs without a Jupyter server
Author-email: Jeremy Howard <j@fast.ai>
License-Expression: Apache-2.0 AND BSD-3-Clause
Project-URL: Repository, https://github.com/AnswerDotAI/execnb/
Project-URL: Documentation, https://AnswerDotAI.github.io/execnb/
Keywords: some,keywords
Classifier: Natural Language :: English
Classifier: Intended Audience :: Developers
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: LICENSE-IPython
License-File: LICENSE-matplotlib-inline
Requires-Dist: fastcore>=2.2.34
Provides-Extra: ipython
Requires-Dist: ipython; extra == "ipython"
Provides-Extra: dev
Requires-Dist: matplotlib; extra == "dev"
Requires-Dist: Pillow; extra == "dev"
Requires-Dist: mistletoe; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Dynamic: license-file

# execnb


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Install

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).

## How to use

[`CaptureShell`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell) runs cell strings and captures notebook outputs without a notebook file or a Jupyter server. By default it uses IPython if installed, or the built-in lean shell otherwise. To require real IPython, pass `use_ipython=True`. To select lean explicitly, create `CaptureShell(use_ipython=False)` before anything imports IPython. All shells 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`:

``` python
from execnb.shell import *
from fastcore.utils import *
from fastcore.nbio import *
```

``` python
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`:

``` python
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`](https://AnswerDotAI.github.io/execnb/shell.html#exec_nb):

``` python
!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

## Parsing notebook commands

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:

``` python
from execnb.minipy.inputtransformer2 import TransformerManager, TokenTransformBase, make_tokens_by_line
```

``` python
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)`.
