Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience function for executing notebooks #573

Merged
merged 2 commits into from
Apr 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions nbconvert/preprocessors/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,3 +391,25 @@ def run_cell(self, cell, cell_index=0):
outs.append(out)

return outs


def executenb(nb, cwd=None, **kwargs):
"""Execute a notebook's code, updating outputs within the notebook object.

This is a convenient wrapper around ExecutePreprocessor. It returns the
modified notebook object.

Parameters
----------
nb : NotebookNode
The notebook object to be executed
cwd : str, optional
If supplied, the kernel will run in this directory
kwargs :
Any other options for ExecutePreprocessor, e.g. timeout, kernel_name
"""
resources = {}
if cwd is not None:
resources['metadata'] = {'path': cwd}
ep = ExecutePreprocessor(**kwargs)
return ep.preprocess(nb, resources)[0]
13 changes: 12 additions & 1 deletion nbconvert/preprocessors/tests/test_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import sys

from .base import PreprocessorTestsBase
from ..execute import ExecutePreprocessor, CellExecutionError
from ..execute import ExecutePreprocessor, CellExecutionError, executenb

from nbconvert.filters import strip_ansi
from nose.tools import assert_raises, assert_in
Expand Down Expand Up @@ -222,3 +222,14 @@ def test_custom_kernel_manager(self):
for method, call_count in expected:
self.assertNotEqual(call_count, 0, '{} was called'.format(method))

def test_execute_function(self):
# Test the executenb() convenience API
current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')

with io.open(filename) as f:
input_nb = nbformat.read(f, 4)

original = copy.deepcopy(input_nb)
executed = executenb(original, os.path.dirname(filename))
self.assert_notebooks_equal(original, executed)