How to use the nbformat.v4.writes 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 root-project / root / documentation / doxygen / converttonotebook.py View on Github external
text += "\n#  \n# Draw all canvases \n# \n%jsroot on\ngROOT->GetListOfCanvases()->Draw()"
        if extension == "py":
            text += "\n#  \n# Draw all canvases \n# \n%jsroot on\nfrom ROOT import gROOT \ngROOT.GetListOfCanvases().Draw()"

    elif not nodraw:
        if isCpp():
            text += "\n#  \n# Draw all canvases \n# \ngROOT->GetListOfCanvases()->Draw()"
        if extension == "py":
            text += "\n#  \n# Draw all canvases \n# \nfrom ROOT import gROOT \ngROOT.GetListOfCanvases().Draw()"

    # Create a notebook from the working text
    nbook = v3.reads_py(text)
    nbook = v4.upgrade(nbook)  # Upgrade v3 to v4

    # Load notebook string into json format, essentially creating a dictionary
    json_data = json.loads(v4.writes(nbook))

    # add the corresponding metadata
    if extension == "py":
        json_data['metadata'] = {
            "kernelspec": {
                "display_name": "Python " + str(sys.version_info[0]),
                "language": "python",
                "name": "python" + str(sys.version_info[0])
            },
            "language_info": {
                "codemirror_mode": {
                    "name": "ipython",
                    "version": 2
                },
                "file_extension": ".py",
                "mimetype": "text/x-python",
github justindujardin / mathy / libraries / website / tools / write_ipynb.py View on Github external
if header_installs is False:
                raise ValueError(
                    "All !pip install comments must be the first lines in a snippet."
                    f" Found the following line after a non-install comment: {line}"
                )
            # output without the comment so ipynb installs the requirement
            out_lines.append(line[1:])
            continue
        # The header installs must be the first (n) lines in a file. After the
        # first non-comment, nothing will be installed.
        header_installs = False
        out_lines.append(line)
    text = "".join(out_lines)
    nbook = v4.upgrade(v3.reads_py(f"{header}{text}"))
    with open(to_file, "w") as fpout:
        fpout.write(f"{v4.writes(nbook)}\n")
github gatsoulis / py2ipynb / py2ipynb.py View on Github external
def py2ipynb_default(input, output):
    with open(input) as f:
        code = f.read()
    code += """
# 

# If you can read this, reads_py() is no longer broken!
"""

    nbook = v3.reads_py(code)
    nbook = v4.upgrade(nbook)  # Upgrade v3 to v4
    jsonform = v4.writes(nbook) + "\n"

    with open(output, "w") as f:
        f.write(jsonform)
github dalejung / nbx / nbx / nbmanager / gist.py View on Github external
Converts a IPython notebook model to a github.Gist `files` dict.
    Parameters
    __________
    model : dict
        Notebook model as specified by the NotebookManager. There is
        an additional `__files` dict of the form {filename: file_content}

    Returns
    -------
    files : dict
        {filename: content}
        Note: changed files dict values to be strings.
    """
    files = {}
    name = model['name']
    content = current.writes(model['content'])
    files[name] = content

    __files = model.get('__files', {})
    for fn, content in __files.items():
        files[fn] = content
    return files
github pyx-project / pyx / www / mkipynb.py View on Github external
bendpattern = re.compile("^!+", re.MULTILINE)
bendcode = '<img align="left" src="http://pyx.sourceforge.net/bend.png">'
description = re.sub(bendpattern, lambda m: bendcode*(m.end()-m.start()), description)
code = open("{}.py".format(filename), encoding="utf-8").read()
code = re.sub('\.writeEPSfile\(("[a-z]+")?\)\n.*writePDFfile\(("[a-z]+")?\)\n.*writeSVGfile\(("[a-z]+")?\)\n', "", code)

nb = nbf.new_notebook()
cells = []
cells.append(nbf.new_markdown_cell(source="# " + title))
cells.append(nbf.new_code_cell(source=code, execution_count=1,
                               outputs=[nbf.new_output(output_type=u'execute_result', execution_count=1,
                                                       data={'image/png': base64.encodebytes(open("{}.png".format(filename), "rb").read()).decode("ascii"),
                                                             'image/svg+xml': open("{}.svg".format(filename), "r", encoding="utf-8").read()})]))
cells.append(nbf.new_markdown_cell(source=description))
nb = nbf.new_notebook(cells=cells, metadata={'language': 'python'})
open("{}.ipynb".format(filename), "w").write(nbf.writes(nb))
github google / or-tools / tools / export_to_ipynb.py View on Github external
# remove start and de-indent lines
        c_lines = lines[s+1:e]
        spaces_to_delete = c_block.body[0].col_offset
        fixed_lines = [n_line[spaces_to_delete:] if n_line.startswith(' '*spaces_to_delete)
                       else n_line for n_line in c_lines]
        fixed_text = '\n'.join(fixed_lines)
        print('Unwrapping main function')
        full_text += fixed_text
    else:
        print('appending', c_block)
        full_text += c_text + '\n'

nbook['cells'].append(v4.new_code_cell(full_text))


jsonform = v4.writes(nbook) + '\n'
output = input
output = output.replace('.py', '.ipynb')
output = output.replace('examples/python', 'examples/notebook')
print('writing %s' % output)
with open(output, "w") as fpout:
    fpout.write(jsonform)
github Autodesk / molecular-design-toolkit / moldesign / _notebooks / nbscripts / strip_nb_output.py View on Github external
"""strip the outputs from a notebook object"""
    nb.metadata.pop('widgets', None)

    for cell in nb.cells:
        if 'outputs' in cell:
            cell['outputs'] = []
        if 'execution_count' in cell:
            cell['execution_count'] = None
        if 'metadata' in cell:
            cell['metadata'] = {}
    return nb

if __name__ == '__main__':
    nb = v4.reads(sys.stdin.read())
    nb = strip_output(nb)
    output = v4.writes(nb)
    if type(output) == str and PY2:
        output = output.encode('utf-8')
    sys.stdout.write(output)