How to use the nbformat.write function in nbformat

To help you get started, we’ve selected a few nbformat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / msticpy / tests / test_timeseries.py View on Github external
def test_timeseries_controls(self):
        nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
        abs_path = Path(_NB_FOLDER).absolute()
        with open(nb_path) as f:
            nb = nbformat.read(f, as_version=4)
        ep = ExecutePreprocessor(timeout=600, kernel_name="python3")

        try:
            ep.preprocess(nb, {"metadata": {"path": abs_path}})
        except CellExecutionError:
            nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
            msg = f"Error executing the notebook '{nb_path}'.\n"
            msg += f"See notebook '{nb_err}' for the traceback."
            print(msg)
            with open(nb_err, mode="w", encoding="utf-8") as f:
                nbformat.write(nb, f)
            raise
github StochSS / stochss / stochss / handlers / util / convert_to_2d_param_sweep_notebook.py View on Github external
cells.append(nbf.new_code_cell(psweep_config_cell))
    except KeyError as err:
        raise JSONFileNotModelError("The JSON file is not formatted as a StochSS model "+str(err))
    # Parameter Sweep Execution cell
    cells.append(nbf.new_code_cell(generate_parameter_sweep_run_cell(get_algorithm(gillespy2_model, is_ssa_c), settings)))
    # Parameter Sweet Plot Cell
    cells.append(nbf.new_code_cell('ps.plot()'))
    # Parameter Sweet Plotly Cell
    cells.append(nbf.new_code_cell('ps.plotplotly()'))
    # Append cells to worksheet
    nb = nbf.new_notebook(cells=cells)

    # Open and write to file
    dest_file = get_unique_file_name('{}2dParamSweep.ipynb'.format(name), dest_path)[0]
    with open(dest_file, 'w') as f:
        nbformat.write(nb, f, version=4)
    f.close()

    return {"Message":'{0} successfully created'.format(dest_file),"FilePath":dest_file.replace(user_dir+'/', ""),"File":dest_file.split('/').pop()}
github jupyter / nbdime / nbdime / webapp / nbdimeserver.py View on Github external
# filename as a commandline argument:
        fn = self.params.get('outputfilename', None)
        if not fn:
            raise web.HTTPError(400, 'Server does not accept storing merge result.')
        path = os.path.join(self.curdir, fn)
        logger.info('Saving merge result in %s', path)

        body = json.loads(escape.to_unicode(self.request.body))
        merged = body['merged']
        merged_nb = nbformat.from_dict(merged)

        # Somehow store unsolved conflicts?
        # conflicts = body['conflicts']

        with io.open(path, 'w', encoding='utf8') as f:
            nbformat.write(merged_nb, f)
        self.finish()
github msmbuilder / mdentropy / docs / sphinxext / notebook_sphinxext.py View on Github external
f['eval'] = "{destdir}/{nbname}.eval.ipynb".format(**f)
        f['py'] = "{destdir}/{nbname}.py".format(**f)

        # 1. Uneval notebook
        shutil.copyfile(f['nbpath'], f['uneval'])
        with open(f['nbpath']) as nb_f:
            nb = nbformat.read(nb_f, as_version=4)
        # 2. Python
        export_python(nb, f['py'])
        # 3. HTML (execute first)
        executer = ExecutePreprocessor(timeout=240)
        executer.preprocess(nb, {})
        html = export_html(nb, f)
        # 4. Eval'd notebook
        with open(f['eval'], 'w') as eval_f:
            nbformat.write(nb, eval_f)

        # Create link to notebook and script files
        link_rst = "({uneval}; {eval}; {py})".format(
            uneval=formatted_link(f['uneval']),
            eval=formatted_link(f['eval']),
            py=formatted_link(f['py']),
        )

        rst_file = self.state_machine.document.attributes['source']
        self.state_machine.insert_input([link_rst], rst_file)

        # create notebook node
        nb_node = notebook_node('', html, format='html', source='nb_path')
        nb_node.source, nb_node.line = (self.state_machine
                                        .get_source_and_line(self.lineno))
github stephenslab / dsc / src / query_jupyter.py View on Github external
def write_notebook(text, output, execute=False):
    import nbformat
    nb = nbformat.reads(text, as_version=4)
    if execute:
        from nbconvert.preprocessors import ExecutePreprocessor
        ep = ExecutePreprocessor(timeout=600, kernel_name='SoS')
        ep.preprocess(nb, {})
    with open(os.path.expanduser(output), 'wt') as f:
        nbformat.write(nb, f)
github ParaToolsInc / taucmdr / packages / taucmdr / analysis / analysis.py View on Github external
"""
        cells = self.get_cells(inputs, *args, **kwargs)
        nb = self._create_notebook_from_cells(cells)

        # If requested, we do an in-place execute of the notebook. Unfortunately, this is
        # less useful than it might otherwise be, as it doesn't take place in a browser and so
        # any commands that require JavaScript to execute won't actually generate output.
        if execute:
            ep = ExecutePreprocessor(timeout=600, kernel_name='python2')
            ep.preprocess(nb, {'metadata': {'path': path}})

        # Finally, we write out the notebook as a version 4 notebook file
        nb_name = filename if filename else "%s-%s.ipynb" % (self.name, uuid.uuid4().hex)
        file_path = os.path.abspath(os.path.join(path, nb_name))
        with open(file_path, 'w') as nb_file:
            nbformat.write(nb, nb_file)
        return file_path
github py4ds / nbless / nbuild.py View on Github external
with open(filename) as f:
            return f.read()

    nb = nbformat.v4.new_notebook()
    md_cell = nbformat.v4.new_markdown_cell
    code_cell = nbformat.v4.new_code_cell

    nb['cells'] = [code_cell(read_file(name))
                   if name.endswith('.py')
                   else md_cell(read_file(name))
                   for name in filenames]

    if not output_path.endswith('/'):
        output_path += '/'

    nbformat.write(nb, output_path+output_name)
github podoc / podoc / podoc / notebook / _notebook.py View on Github external
def dump(self, nb, file_or_path):
        with _get_file(file_or_path, 'w') as f:
            nbformat.write(nb, f, _NBFORMAT_VERSION)