Created
June 14, 2017 10:00
-
-
Save mgalardini/0d41d3c6051705872023ceb65dc71b96 to your computer and use it in GitHub Desktop.
Pass arguments to a Jupyter notebook and save it after re-running it
This file contains hidden or 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
#!/usr/bin/env python | |
''' | |
Run and save a jupyter notebook by providing arguments from the command line | |
Uses the nbparameterise package, and requires the first cell to have variables | |
definitions. | |
Command line parsing based on this Stack Overflow answer: | |
https://stackoverflow.com/a/42355279/1237531 | |
''' | |
from nbparameterise import extract_parameters, parameter_values, replace_definitions | |
import nbformat | |
def get_options(): | |
import argparse | |
args_dict = {} | |
class StoreDictKeyPair(argparse.Action): | |
def __init__(self, option_strings, dest, nargs=None, **kwargs): | |
self._nargs = nargs | |
super(StoreDictKeyPair, self).__init__(option_strings, dest, nargs=nargs, **kwargs) | |
def __call__(self, parser, namespace, values, option_string=None): | |
for kv in values: | |
k,v = kv.split("=") | |
args_dict[k] = v | |
setattr(namespace, self.dest, args_dict) | |
description = "Run a Jupyter notebook by passing arguments to it" | |
parser = argparse.ArgumentParser(description=description, | |
prog='run_notebook.py') | |
parser.add_argument('template', action='store', | |
help='Template notebook') | |
parser.add_argument('output', action='store', | |
help='Output notebook') | |
parser.add_argument('--key-value', | |
dest='args_dict', | |
action=StoreDictKeyPair, | |
nargs='+', | |
metavar='KEY=VAL') | |
return parser.parse_args() | |
if __name__ == '__main__': | |
options = get_options() | |
print(options.args_dict) | |
with open(options.template) as template: | |
nb = nbformat.read(template, as_version=4) | |
orig_parameters = extract_parameters(nb) | |
params = parameter_values(orig_parameters, **options.args_dict) | |
new_nb = replace_definitions(nb, params) | |
with open(options.output, 'w') as output: | |
nbformat.write(new_nb, output) |
can you tell the command to run it using anaconda prompt.
coz we can't directly run it using jupyter notebook we have to pass arguments, so can u tell that command.
like we do it it ubuntu "python3 file.py --image imagefilename"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you tell the command to run it using anaconda prompt.