1

Is it possible for a Python script to write into a iPython Notebook?

with open("my_notebook.ipynb", "w") as jup:
     jup.write("print(\"Hello there!\")")

If there's some package for doing so, can I also control the way cells are split in the notebook?

I'm designing a software tool (that carries out some optimization) to prepare an iPython notebook that can be run on some server performing scientific computations.

I understand that a related solution is to output to a Python script and load it within a iPython Notebook using %load my_python_script.py. However, that involves a user to type stuff that I would ideally like to avoid.

1 Answer 1

3

Look at the nbformat repo on Github. The reference implementation is shown there.

From their docs

Jupyter (né IPython) notebook files are simple JSON documents, containing text, source code, rich media output, and metadata. Each segment of the document is stored in a cell.

It also sounds like you want to create the notebook programmatically, so you should use the NotebookNode object.

For the code, something like, should get you what you need. new_cell_code should be used if you have code cells versus just plain text cells. Text cells should use the existing markdown formatting.

import nbformat

notebook = nbformat.v4.new_notebook()


text = """Hello There """



notebook['cells'] = [nbformat.v4.new_markdown_cell(text)]
notebook= nbformat.v4.new_notebook()
nbformat.write(notebook,'filename.ipynb')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.