How to use the nbformat.v4.new_output 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 alexisfcote / offline_slides / tests / test_integration.py View on Github external
def setUp(self):
        self.tmpdir = tempfile.TemporaryDirectory()

        nb = new_notebook()

        nb.cells.append(new_markdown_cell(u'Created by test ³'))
        cc1 = new_code_cell(source=u'print(2*6)')
        cc1.outputs.append(new_output(output_type="stream", text=u'12'))
        cc1.outputs.append(new_output(output_type="execute_result",
                                      data={'image/png': png_green_pixel},
                                      execution_count=1,
                                      ))
        nb.cells.append(cc1)

        with io.open(pjoin(self.tmpdir.name, 'testnb.ipynb'), 'w',
                     encoding='utf-8') as f:
            write(nb, f, version=4)
github dataflownb / dfkernel / dfkernel / nbtests / test_files.py View on Github external
def test_contents_manager(self):
        "make sure ContentsManager returns right files (ipynb, bin, txt)."

        nbdir = self.notebook_dir

        nb = new_notebook(
            cells=[
                new_markdown_cell(u'Created by test ³'),
                new_code_cell("print(2*6)", outputs=[
                    new_output("stream", text="12"),
                ])
            ]
        )

        with io.open(pjoin(nbdir, 'testnb.ipynb'), 'w', 
            encoding='utf-8') as f:
            write(nb, f, version=4)

        with io.open(pjoin(nbdir, 'test.bin'), 'wb') as f:
            f.write(b'\xff' + os.urandom(5))
            f.close()

        with io.open(pjoin(nbdir, 'test.txt'), 'w') as f:
            f.write(u'foobar')
            f.close()
github alexisfcote / offline_slides / tests / test_integration.py View on Github external
def setUp(self):
        self.tmpdir = tempfile.TemporaryDirectory()

        nb = new_notebook()

        nb.cells.append(new_markdown_cell(u'Created by test ³'))
        cc1 = new_code_cell(source=u'print(2*6)')
        cc1.outputs.append(new_output(output_type="stream", text=u'12'))
        cc1.outputs.append(new_output(output_type="execute_result",
                                      data={'image/png': png_green_pixel},
                                      execution_count=1,
                                      ))
        nb.cells.append(cc1)

        with io.open(pjoin(self.tmpdir.name, 'testnb.ipynb'), 'w',
                     encoding='utf-8') as f:
            write(nb, f, version=4)
github elehcimd / nb2md / nb2md / nb2md.py View on Github external
elif not source.startswith("%") or \
                    source.startswith("%sh") or \
                    source.startswith("%spark.dep") or \
                    source.startswith("%pyspark") or \
                    source.startswith("%spark") or \
                    source.startswith("%sql"):
                count_cells_code += 1
                execution_count += 1
                outputs = []

                results = paragraph.get("results", {})
                msgs = results.get("msg", [])
                for msg in msgs:
                    if msg["type"] == "TEXT":
                        outputs.append(nbf.v4.new_output("execute_result", {'text/plain': [msg["data"]]},
                                                         execution_count=execution_count))
                    elif msg["type"] == "TABLE":
                        outputs.append(nbf.v4.new_output("execute_result", {'text/plain': [msg["data"]]},
                                                         execution_count=execution_count))
                    elif msg["type"] == "HTML":
                        outputs.append(nbf.v4.new_output("execute_result", {'text/html': [msg["data"]]},
                                                         execution_count=execution_count))

                    else:
                        print("Warning: unsupported output type: '{}'".format(msg["type"]))
                        print(msg)

                cell = nbf.v4.new_code_cell(source=source, execution_count=execution_count, outputs=outputs)
                self.nb['cells'].append(cell)

            else:
github nteract / papermill / papermill / execute.py View on Github external
error = PapermillExecutionError(
                    exec_count=cell.execution_count,
                    source=cell.source,
                    ename=output.ename,
                    evalue=output.evalue,
                    traceback=output.traceback,
                )
                break

    if error:
        # Write notebook back out with the Error Message at the top of the Notebook.
        error_msg = ERROR_MESSAGE_TEMPLATE % str(error.exec_count)
        error_msg_cell = nbformat.v4.new_code_cell(
            source="%%html\n" + error_msg,
            outputs=[
                nbformat.v4.new_output(output_type="display_data", data={"text/html": error_msg})
            ],
            metadata={"inputHidden": True, "hide_input": True},
        )
        nb.cells = [error_msg_cell] + nb.cells
        write_ipynb(nb, output_path)
        raise error
github broadinstitute / rnaseqc / python / nb_encode.py View on Github external
def encode_plot_cell(cell, source, result, figure):
    img = io.BytesIO()
    figure.savefig(img)
    img.seek(0,0)
    img = base64.b64encode(img.read())
    output_cell = nbf.v4.new_code_cell(
        source,
        outputs=[
            nbf.v4.new_output(
                'execute_result',
                {
                    'text/plain': [result]
                },
                execution_count=cell
            ),
            nbf.v4.new_output(
                'display_data',
                {
                    'text/plain': [repr(figure)],
                    'image/png': img.decode()
                }
            )
        ]
    )
    return output_cell
github rossant / ipymd / ipymd / formats / notebook.py View on Github external
def append_code(self, input, output=None, image=None, metadata=None):
        input = self._code_filter(input)
        cell = nbf.v4.new_code_cell(input,
                                    execution_count=self._count,
                                    metadata=metadata)
        if output:
            cell.outputs.append(nbf.v4.new_output('execute_result',
                                {'text/plain': output},
                                execution_count=self._count,
                                metadata={},
                                ))
        if image:
            # TODO
            raise NotImplementedError("Output images not implemented yet.")
        self._nb['cells'].append(cell)
        self._count += 1
github broadinstitute / rnaseqc / python / nb_encode.py View on Github external
def encode_figure(figure, **kwargs):
    img = io.BytesIO()
    figure.savefig(img, **kwargs)
    img.seek(0,0)
    return nbf.v4.new_output(
        'display_data',
        {
            'text/plain': [repr(figure)],
            'image/png': base64.b64encode(img.read()).decode()
        }
github broadinstitute / rnaseqc / python / nb_encode.py View on Github external
def encode_dataframe(df, n, **kwargs):
    return nbf.v4.new_output(
        'execute_result',
        {
            'text/plain': [df.to_string()],
            'text/html': [df.to_html(**kwargs)]
        },
        execution_count=n
    )