---
title: shell
description: A shell for running notebook code without a notebook server
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

```python
from fastcore.ansi import ansi2html
from IPython.display import HTML
from fastcore.test import *
from base64 import b64decode
from io import BytesIO
from PIL import Image
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L70)

### leading\_comment\_lines

```python
def leading_comment_lines(
    lines
):
```

*Input cleanup transform: drop leading blank/comment lines when the first code line is a cell magic, which IPython otherwise misparses as a line magic*

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L80)

### CaptureShell

```python
def CaptureShell(
    path:str | pathlib._local.Path=None, mpl_format:str='retina', history:bool=False, timeout:int | None=None, *,
    use_ipython:bool | None=None,
    cache_size:int | None=None, # IPython numbered output cache size; 0 disables it, None keeps IPython's default
):
```

*Create a shell for captured execution. Importing IPython or selecting minipy fixes the backend for this process.*

Each shell runs cells on a private event loop in a background thread. `run` waits for the result, whether called from a script or another notebook. A timeout bounds that wait even when synchronous code blocks the loop. Discard a timed-out shell if its code is still running.

Capture includes the post-execution callbacks, so inline plots appear alongside explicit displays and the final expression.

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L108)

### capture\_output

```python
def capture_output(
    stdout:bool=True, stderr:bool=True, display:bool=True
):
```

*Capture stdout, stderr, and rich displays from the active shell. Without a shell, capture only streams.*

### Cells / run

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L125)

### format\_exc

```python
def format_exc(
    e
):
```

*Format exception `e` as a string list*

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L130)

### NbResult

```python
def NbResult(
    *args, **kwargs
):
```

*Built-in mutable sequence.*

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L166)

### \_CaptureShell.run

```python
def run(
    code:str, # Python/IPython code to run
    stdout:bool=True, # Capture stdout and save as output?
    stderr:bool=True, # Capture stderr and save as output?
    timeout:Optional[int]=None, # Seconds before the run times out (None: `self.timeout`)
    verbose:bool=False, # Show stdout/stderr during execution
    grace:float=5, # Seconds to wait for cancellation after a timeout
):
```

*Run `code` on the shell's loop, returning a list of all outputs in Jupyter notebook format*

A trailing semicolon suppresses the final expression, even with a comment after it. A cell magic's body is data supplied to the magic, so a semicolon in that body does not suppress its result. Captured streams are unaffected:

```python
cs = CaptureShell(mpl_format=None)
cs.register_magic_function(lambda line, cell: 'visible', 'cell', 'visible')
res = cs.run("%%visible\npayload;")
test_eq(res[0]['data']['text/plain'], ["'visible'"])
test_eq(cs.run("1+1;"), [])
test_eq(cs.run("print('kept'); 2;"), [dict(output_type='stream', name='stdout', text=['kept\n'])])
```

```python
s = CaptureShell()
```

```python
s.run("print(1)")
```

```output
[{'name': 'stdout', 'output_type': 'stream', 'text': ['1\n']}]
```

Code can include magics and `!` shell commands:

```python
o = s.run("%time 1+1")
o
```

```output
[{'name': 'stdout',
  'output_type': 'stream',
  'text': ['CPU times: user 1e+03 ns, sys: 0 ns, total: 1e+03 ns\n',
   'Wall time: 1.91 us\n']},
 {'data': {'text/plain': ['2']},
  'metadata': {},
  'output_type': 'execute_result',
  'execution_count': None}]
```

By default, only the final expression is displayed. Set `s.ast_node_interactivity = 'all'` to keep every displayed expression in the notebook output. In either mode, `s.result` holds the last displayed Python value, or `None` if there was none:

```python
s.result
```

```output
2
```

A trailing `;` stops the result from being captured:

```python
s.run("1+2;")
```

```output
[]
```

Code running inside a cell can itself call `run_cell` (the `%%capture` magic does exactly that). Such nested calls behave exactly as in plain IPython. They return an `ExecutionResult`, and their output flows to the enclosing capture context, so `%%capture` works:

```python
s.run("%%capture c\nprint(1)")
test_eq(s.user_ns['c'].stdout, '1\n')
s.run("r = get_ipython().run_cell('7')")
test_eq(s.user_ns['r'].__class__.__name__, 'ExecutionResult')
```

IPython requires a cell magic to be the very first line of a cell: even a comment above it makes the `%%foo` line parse as a *line* magic named `%foo`, which fails with a confusing "Line magic function `%%foo` not found" error. [`CaptureShell`](shell.md#captureshell) smooths both edges: leading blank and comment lines above a cell magic are dropped (extending IPython's own `leading_empty_lines` cleanup), and when real code precedes the magic (which can't be auto-fixed), the error message explains the actual problem.

```python
s.run('# a narration comment\n\n%%capture c2\nprint(2)')
test_eq(s.exc, None)
test_eq(s.user_ns['c2'].stdout, '2\n')
```

```python
s.run('a=1\n%%capture c3\nprint(3)')
assert 'must start the cell' in str(s.exc)
```

Exceptions raised by cell code are returned as error outputs:

```python
o = s.run("1/0")
o
```

```output
[{'name': 'stdout',
  'output_type': 'stream',
  'text': ['\x1b[31m---------------------------------------------------------------------------\x1b[39m\n',
   '\x1b[31mZeroDivisionError\x1b[39m                         Traceback (most recent call last)\n',
   '\x1b[36mFile \x1b[39m\x1b[32m<ipython-input-1-9e1622b385b6>:1\x1b[39m\n',
   '\x1b[32m----> \x1b[39m\x1b[32m1\x1b[39m \x1b[30;43m1\x1b[39;49m\x1b[30;43m/\x1b[39;49m\x1b[30;43m0\x1b[39;49m\n',
   '\n',
   '\x1b[31mZeroDivisionError\x1b[39m: division by zero\n']},
 {'ename': 'ZeroDivisionError',
  'evalue': 'division by zero',
  'output_type': 'error',
  'traceback': ['Traceback (most recent call last):\n',
   '  File "/Users/jhoward/aai-ws/.venv/lib/python3.13/site-packages/IPython/core/interactiveshell.py", line 3748, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)\n    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',
   '  File "<ipython-input-1-9e1622b385b6>", line 1, in <module>\n    1/0\n    ~^~\n',
   'ZeroDivisionError: division by zero\n']}]
```

Pass `timeout` to bound execution time; a cell that exceeds it returns a `TimeoutError` output and sets `s.exc`:

```python
s.run("import time; time.sleep(0.1); print('no timeout')", timeout=1)
```

```output
[{'name': 'stdout', 'output_type': 'stream', 'text': ['no timeout\n']}]
```

```python
o = s.run("import time; time.sleep(1.1)", timeout=1)
test_eq(o[0]['ename'], 'TimeoutError')
s.exc
```

```output
['\x1b[31m---------------------------------------------------------------------------\x1b[39m\n',
 '\x1b[31mTimeoutError\x1b[39m                              Traceback (most recent call last)\n']
```

Streams, rich displays, and the final expression are captured in order:

```python
o1 = s.run('from IPython.display import Markdown,display; print(0); print(1); display(Markdown("*2*")); Markdown("*1*")')
o1
```

```output
[{'name': 'stdout', 'output_type': 'stream', 'text': ['0\n', '1\n']},
 {'data': {'text/plain': ['Markdown(*2*)'], 'text/markdown': ['*2*']},
  'metadata': {},
  'output_type': 'display_data'},
 {'data': {'text/plain': ['Markdown(*1*)'], 'text/markdown': ['*1*']},
  'metadata': {},
  'output_type': 'execute_result',
  'execution_count': None}]
```

```python
oaw = render_text(s.run("import asyncio\nawait asyncio.sleep(0.01)\n7"))
test_is('7' in oaw, True)
```

Async line and cell magics are awaited too, so a magic can return a coroutine:

```python
async def shout(line, cell): return cell.upper()
s.register_magic_function(shout, 'cell')
test_is('HI' in render_text(s.run('%%shout\nhi')), True)
```

An unhandled exception becomes a notebook error output. Suppress its printed traceback so it appears only once. When a `%run` script reports an error and the cell continues, keep the traceback in the captured output.

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L193)

### \_CaptureShell.showtraceback

```python
def showtraceback(
    *args, **kwargs
):
```

*Print errors handled inside the cell; run() returns unhandled errors as notebook outputs*

An unhandled exception with no preceding output produces one notebook error:

```python
s = CaptureShell()
for code in ('1/0', 'if :'): test_eq([x['output_type'] for x in s.run(code)], ['error'])
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L202)

### render\_outputs

```python
def render_outputs(
    outputs, ansi_renderer:function=_strip, include_imgs:bool=True, pygments:bool=False, md_tfm:function=noop,
    html_tfm:function=noop
):
```

```python
HTML(render_outputs(o))
```

We can use `ansi2html` to convert from ANSI to HTML for color rendering.  You need some [css styles](https://github.com/fastai/fastcore/blob/master/examples/ansi.css) for the colors to render properly.  Jupyter already has these built in so it's not neccessary here, but if you plan on using this in another web app you will need to ensure that css styling is included.

```python
HTML(render_outputs(o, ansi2html))
```

Images and matplotlib figures are captured:

```python
res = s.run('''import matplotlib.pyplot as plt
plt.figure(figsize=(2,1))
plt.plot([1,2,4]);''')

HTML(render_outputs(res))
```

If an exception is raised then the exception type, object, and stacktrace are stored in `exc`:

```python
o = s.run('raise Exception("Oops")')
o
```

```output
[{'name': 'stdout',
  'output_type': 'stream',
  'text': ['\x1b[31m---------------------------------------------------------------------------\x1b[39m\n',
   '\x1b[31mException\x1b[39m                                 Traceback (most recent call last)\n',
   '\x1b[36mCell\x1b[39m\x1b[36m \x1b[39m\x1b[32mIn[1]\x1b[39m\x1b[32m, line 1\x1b[39m\n',
   '\x1b[32m----> \x1b[39m\x1b[32m1\x1b[39m \x1b[38;5;28;01mraise\x1b[39;00m \x1b[38;5;167;01mException\x1b[39;00m(\x1b[33m"\x1b[39m\x1b[33mOops\x1b[39m\x1b[33m"\x1b[39m)\n',
   '\n',
   '\x1b[31mException\x1b[39m: Oops\n']},
 {'ename': 'Exception',
  'evalue': 'Oops',
  'output_type': 'error',
  'traceback': ['Traceback (most recent call last):\n',
   '  File "/Users/jhoward/aai-ws/.venv/lib/python3.13/site-packages/IPython/core/interactiveshell.py", line 3748, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)\n    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',
   '  File "<ipython-input-1-01648acb07bd>", line 1, in <module>\n    raise Exception("Oops")\n',
   'Exception: Oops\n']}]
```

```python
s.exc
```

```output
Exception('Oops')
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L235)

### \_CaptureShell.cell

```python
def cell(
    cell, stdout:bool=True, stderr:bool=True, verbose:bool=False, timeout=None
):
```

*Run `cell`, skipping if not code, and store outputs (and the execution count) back in cell*

```python
clean = Path('../tests/clean.ipynb')
nb = read_nb(clean)
c = nb.cells[1]
c
```

```python
{ 'cell_type': 'code',
  'execution_count': None,
  'id': 'b123d6d0',
  'idx_': 1,
  'metadata': {},
  'outputs': [],
  'source': 'print(1)\n2'}
```

```python
s.cell(c)
c.outputs
```

```output
[{'name': 'stdout', 'output_type': 'stream', 'text': ['1\n']},
 {'data': {'text/plain': ['2']},
  'metadata': {},
  'output_type': 'execute_result',
  'execution_count': None}]
```

Re-running a cell that no longer produces output clears its stale outputs:

```python
c2 = read_nb(clean).cells[1]
s.cell(c2)
assert c2.outputs
c2.source = 'x = 1'
s.cell(c2)
test_eq(c2.outputs, [])
```

`cell` also records how long the run took, in the `metadata.execution` dict that Jupyter's `record_timing` option uses: ISO 8601 timestamps under the standard message-key names, plus a `total` key holding elapsed seconds for programmatic use (`run_all`'s `postproc` receives the cell right after these are stamped). In a fastship project `ship-clean` strips this metadata, so it stays out of committed notebooks unless allowed with `allowed_cell_metadata_keys`.

```python
timing = c.metadata.execution
assert 0 <= timing['total'] < 10
test_eq(set(timing), {'iopub.execute_input','shell.execute_reply','total'})
list(timing)
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L248)

### find\_output

```python
def find_output(
    outp, # Output from `run`
    ot:str='execute_result', # Output_type to find
):
```

*Find first output of type `ot` in `CaptureShell.run` output*

```python
find_output(c.outputs)['data']
```

```python
{'text/plain': ['2']}
```

```python
find_output(c.outputs, 'stream')['text']
```

```output
['1\n']
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L256)

### out\_exec

```python
def out_exec(
    outp
):
```

*Get data from execution result in `outp`.*

```python
out_exec(c.outputs)
```

```output
'2'
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L262)

### out\_stream

```python
def out_stream(
    outp
):
```

*Get text from stream in `outp`.*

```python
out_stream(c.outputs)
```

```output
'1'
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L268)

### out\_error

```python
def out_error(
    outp
):
```

*Get traceback from error in `outp`.*

[`out_error`](shell.md#out_error) extracts the formatted traceback string from an error output:

```python
assert 'Oops' in out_error(o)
out_error(o)
```

### NBs

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L292)

### \_CaptureShell.run\_all

```python
def run_all(
    nb, # A notebook read with `nbclient` or `read_nb`
    exc_stop:bool=False, # Stop on exceptions?
    preproc:<built-in function callable>=_false, # Called before each cell is executed
    postproc:<built-in function callable>=_false, # Called after each cell is executed
    inject_code:str | None=None, # Code to inject into a cell
    inject_idx:int=0, # Cell to replace with `inject_code`
    verbose:bool=False, # Show stdout/stderr during execution
    cell_timeout:int=None, # Seconds before each cell times out (None: no limit)
    grace:float=5, # Seconds to wait for cancellation before giving up
):
```

*Run all cells in `nb`, stopping at first exception if `exc_stop`; tasks a run leaves behind are cancelled, with survivors in `self.leaks`*

```python
nb.cells[2].outputs
```

```output
[]
```

```python
s.run_all(nb)
nb.cells[2].outputs
```

```output
[{'data': {'text/plain': ['<IPython.core.display.Markdown object>'],
   'text/markdown': ["This is *bold*. Here's a [link](https://www.fast.ai)."]},
  'metadata': {},
  'output_type': 'execute_result',
  'execution_count': None}]
```

With `exc_stop=False` (the default), execution continues after exceptions, and exception details are stored into the appropriate cell's output:

```python
nb.cells[-1].source
```

```output
'raise Exception("Oopsie!")'
```

```python
nb.cells[-1].outputs
```

```output
[{'name': 'stdout',
  'output_type': 'stream',
  'text': ['\x1b[31m---------------------------------------------------------------------------\x1b[39m\n',
   '\x1b[31mException\x1b[39m                                 Traceback (most recent call last)\n',
   '\x1b[36mCell\x1b[39m\x1b[36m \x1b[39m\x1b[32mIn[1]\x1b[39m\x1b[32m, line 1\x1b[39m\n',
   '\x1b[32m----> \x1b[39m\x1b[32m1\x1b[39m \x1b[38;5;28;01mraise\x1b[39;00m \x1b[38;5;167;01mException\x1b[39;00m(\x1b[33m"\x1b[39m\x1b[33mOopsie!\x1b[39m\x1b[33m"\x1b[39m)\n',
   '\n',
   '\x1b[31mException\x1b[39m: Oopsie!\n']},
 {'ename': 'Exception',
  'evalue': 'Oopsie!',
  'output_type': 'error',
  'traceback': ['Traceback (most recent call last):\n',
   '  File "/Users/jhoward/aai-ws/.venv/lib/python3.13/site-packages/IPython/core/interactiveshell.py", line 3748, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)\n    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',
   '  File "<ipython-input-1-1c97c1d317ab>", line 1, in <module>\n    raise Exception("Oopsie!")\n',
   'Exception: Oopsie!\n']}]
```

With `exc_stop=True`, exceptions in a cell are raised and no further processing occurs:

```python
try: s.run_all(nb, exc_stop=True)
except Exception as e: print(f"got exception: {e}")
```

```output
got exception: Oopsie!
```

A hung cell can't hang the caller: `cell_timeout` bounds each cell at the submission boundary, recording a `TimeoutError` (including the stacks of the loop's pending tasks) as the cell's output. When the run ends, tasks it started but never finished are cancelled, with any that refuse to die left in `leaks`:

```python
s2 = CaptureShell(mpl_format=None)
nb2 = new_nb([mk_cell('import asyncio'), mk_cell('t = asyncio.ensure_future(asyncio.sleep(60))'), mk_cell('await asyncio.sleep(60)')])
s2.run_all(nb2, cell_timeout=1, grace=1)
test_eq(nb2.cells[-1].outputs[0]['ename'], 'TimeoutError')
test_eq(s2.leaks, [])
test_eq(s2.user_ns['t'].cancelled(), True)
```

Cancellation needs the loop: a cell blocking in *sync* code pins the loop, so nothing can be delivered to it. The timeout still returns on schedule -- the caller is never hung -- but the shell's thread stays stuck inside the cell, the stuck tasks land in `leaks`, and the shell should be discarded:

```python
s3 = CaptureShell(mpl_format=None)
nb3 = new_nb([mk_cell('import time'), mk_cell('time.sleep(4)')])
s3.run_all(nb3, cell_timeout=1, grace=0.2)
test_eq(nb3.cells[-1].outputs[0]['ename'], 'TimeoutError')
assert s3.leaks
```

We can pass a function to `preproc` to have it run on every cell. It can modify the cell as needed. If the function returns `True`, then that cell will not be executed. For instance, to skip the cell which raises an exception:

```python
nb = read_nb(clean)
s.run_all(nb, preproc=lambda c: 'raise' in c.source)
```

This cell will contain no output, since it was skipped.

```python
nb.cells[-1].outputs
```

```output
[]
```

```python
nb.cells[1].outputs
```

```output
[{'name': 'stdout', 'output_type': 'stream', 'text': ['1\n']},
 {'data': {'text/plain': ['2']},
  'metadata': {},
  'output_type': 'execute_result',
  'execution_count': None}]
```

You can also pass a function to `postproc` to modify a cell after it is executed.

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L317)

### \_CaptureShell.execute

```python
def execute(
    src:str | pathlib._local.Path, # Notebook path to read from
    dest:str | None=None, # Notebook path to write to
    exc_stop:bool=False, # Stop on exceptions?
    preproc:<built-in function callable>=_false, # Called before each cell is executed
    postproc:<built-in function callable>=_false, # Called after each cell is executed
    inject_code:str | None=None, # Code to inject into a cell
    inject_path:str | pathlib._local.Path | None=None, # Path to file containing code to inject into a cell
    inject_idx:int=0, # Cell to replace with `inject_code`
    verbose:bool=False, # Show stdout/stderr during execution
    cell_timeout:int=None, # Seconds before each cell times out (None: no limit)
):
```

*Execute notebook from `src` and save with outputs to \`dest*

This is a shortcut for the combination of `read_nb`, `run_all`, and `write_nb`.

```python
s = CaptureShell()
try:
    s.execute(clean, 'tmp.ipynb')
    print(read_nb('tmp.ipynb').cells[1].outputs)
finally: Path('tmp.ipynb').unlink()
```

```output
[{'name': 'stdout', 'output_type': 'stream', 'text': '1\n'}, {'data': {'text/plain': '2'}, 'execution_count': None, 'metadata': {}, 'output_type': 'execute_result'}]
```

```python
p = Path.home()/'git'/'fastcore'/'nbs'
n = p/'03a_parallel.ipynb'
```

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L341)

### \_CaptureShell.prettytb

```python
def prettytb(
    fname:str | pathlib._local.Path=None, # filename to print alongside the traceback
):
```

*Show a pretty traceback for notebooks, optionally printing `fname`.*

If an error occurs while running a notebook, you can retrieve a pretty version of the error with the `prettytb` method:

```python
s = CaptureShell()
try: s.execute('../tests/error.ipynb', exc_stop=True)
except: print(s.prettytb())
```

```output
AssertionError in ../tests/error.ipynb:
===========================================================================

While Executing Cell #2:
Traceback (most recent call last):
  File "<ipython-input-1-5c812627fe60>", line 2, in <module>
    try: s.execute('../tests/error.ipynb', exc_stop=True)
         ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<ipython-input-1-4b062e10fd76>", line 19, in execute
    self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<ipython-input-1-54c4c86f5c38>", line 21, in run_all
    if self.exc and exc_stop: raise self.exc from None
                              ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/jhoward/aai-ws/.venv/lib/python3.13/site-packages/IPython/core/interactiveshell.py", line 3748, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<ipython-input-1-b968a57a586e>", line 3, in <module>
    foo()
    ~~~^^
  File "/Users/jhoward/aai-ws/execnb/tests/err.py", line 2, in foo
    assert 13 == 98
           ^^^^^^^^
AssertionError
```

### render\_text

Downstream kernels (e.g clikernel) print each executed cell's outputs as plain text, so nbio's `render_text` is re-exported here for them. Running notebook cells by id in the current kernel is aidialog's `%nbrun` magic, built on [`fastcore.nbio.select_cells`](https://fastcore.fast.ai/nbio.html#select_cells) and [`fastcore.nbio.run_cell`](https://fastcore.fast.ai/nbio.html#run_cell).

`run_text` names the composition those kernels use: run code and return what a notebook's output area would show, as concise text. One visible output renders bare (markdown-preferred), several arrive in `render_text`'s tagged form, and nothing visible is `''`.

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L358)

### \_CaptureShell.run\_text

```python
def run_text(
    code, # Python/IPython code to run
    *, stdout:bool=True, # Capture stdout and save as output?
    stderr:bool=True, # Capture stderr and save as output?
    timeout:Optional[int]=None, # Seconds before the run times out (None: `self.timeout`)
    verbose:bool=False, # Show stdout/stderr during execution
    grace:float=5, # Seconds to wait for cancellation after a timeout
):
```

*Run `code`, returning its outputs rendered as concise text: what a notebook's output area shows*

```python
s = CaptureShell()
o = s.run_text('print(1); 2')
test_is('1' in o and '2' in o, True)
test_eq(s.run_text('1;'), '')
test_eq(s.run_text("class M:\n    def _repr_markdown_(self): return '**hi**'\nM()"), '**hi**')
test_is('ZeroDivisionError' in s.run_text('1/0'), True)
o
```

[`render_outputs`](shell.md#render_outputs) is HTML-oriented. Downstream kernels print each executed cell's result to stdout instead, so we use fastcore's `render_text`, which renders outputs to concise text.

```python
def is_sublist(sub, lst): return any(lst[i:i+len(sub)] == sub for i in range(len(lst)-len(sub)+1))
```

```python
s2 = CaptureShell()
r = s2.run('from IPython.display import display,Markdown; display(Markdown("x"))')
test_eq(r[0]['output_type'], 'display_data')
r
```

```output
([<IPython.utils.capture.RichOutput>], '')
```

If you pass `inject_code` to `execute` or `run_all`, the source of `nb.cells[inject_idx]` will be replaced with `inject_code`. By default, the first cell is replaced. For instance consider this notebook:

```python
nb = read_nb('../tests/params.ipynb')
for c in nb.cells: print('- ',c.source)
```

```output
-  a=1
-  print(a)
```

We can replace the first cell with `a=2` by passing that as `inject_code`, and the notebook will run with that change:

```python
nb = read_nb('../tests/params.ipynb')
s.run_all(nb, inject_code="a=2")
list(nb.cells)
```

```output
[{'cell_type': 'code',
  'execution_count': None,
  'id': 'a63ce885',
  'metadata': {'time_run': '2026-01-04T20:52:46.502210+00:00'},
  'outputs': [],
  'source': 'a=2',
  'idx_': 0},
 {'cell_type': 'code',
  'execution_count': None,
  'id': 'ea528db5',
  'metadata': {'time_run': '2026-01-04T20:52:46.506607+00:00'},
  'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['2\n']}],
  'source': 'print(a)',
  'idx_': 1}]
```

This can be used with `execute` to parameterise runs of models in notebooks. Place any defaults for configuration code needed in the first cell, and then when running `execute` pass in new parameters as needed in `inject_code`. To replace only some of the defaults, leave an empty cell as the second cell, and inject code using `inject_idx=1` to replace the empty second cell with code that overrides some of the defaults set in the first cell. When using `execute` you can pass `inject_path` instead of `inject_code` to read the injected code from a file.

[source](https://github.com/AnswerDotAI/execnb/blob/main/execnb/shell.py#L364)

### exec\_nb

```python
def exec_nb(
    src:str, # Notebook path to read from
    dest:str='', # Notebook path to write to
    exc_stop:bool=False, # Stop on exceptions?
    inject_code:str=None, # Code to inject into a cell
    inject_path:str=None, # Path to file containing code to inject into a cell
    inject_idx:int=0, # Cell to replace with `inject_code`
    verbose:bool=False, # Show stdout/stderr during execution
    cell_timeout:int=None, # Seconds before each cell times out (None: no limit)
):
```

*Execute notebook from `src` and save with outputs to `dest`*

This is the command-line version of `execute`. Run `exec_nb -h` from the command line to see how to pass arguments. If you don't pass `dest` then the output notebook won't be saved; this is mainly useful for running tests.
