Last active
March 1, 2022 21:18
-
-
Save sam2332/f9adb5f4077d49fe9a13c3091a4fb508 to your computer and use it in GitHub Desktop.
The shortest code to run a jupyter notebook and retrieve the output from all cells.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import nbclient | |
import nbformat | |
import nbparameterise | |
import sys | |
old_stdout = sys.stdout | |
parser = argparse.ArgumentParser( | |
description='Notebook Runner' | |
) | |
parser.add_argument('Notebook') | |
args, unknown = parser.parse_known_args() | |
with open(args.Notebook, 'rb') as f: | |
nb = nbformat.read(f, as_version=4) | |
notebook_params = nbparameterise.extract_parameters(nb) | |
parser = argparse.ArgumentParser() | |
for item in notebook_params: | |
parser.add_argument(f'--{item.name}') | |
args, unknown = parser.parse_known_args() | |
new_params = nbparameterise.parameter_values(old_params,**vars(args)) | |
new_nb = nbparameterise.replace_definitions(nb, new_params) | |
output = nbclient.execute(new_nb) | |
sys.stdout = old_stdout | |
for item in output['cells']: | |
for o in item['outputs']: | |
print(o['text'].strip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment