Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (v4
) API.
Input format
Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desired. Here's a sample input file (original documentation here). The first two lines are ignored, and optional. (In fact, the reader will ignore coding:
and <nbformat>
lines anywhere in the file.)
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# The simplest notebook. Markdown cells are embedded in comments,
# so the file is a valid `python` script.
# Be sure to **leave a space** after the comment character!
# <codecell>
print("Hello, IPython")
# <rawcell>
# Raw cell contents are not formatted as markdown
(The API also accepts the obsolete directives <htmlcell>
and <headingcell level=...>
, which are immediately transformed to other types.)
How to import it
For some reason, this format is not supported by version 4 of the Notebook API. It's still a nice format, so it's worth the trouble to support it by importing into version 3 and upgrading. In principle it's just two lines of code, plus i/o:
from IPython.nbformat import v3, v4
with open("input-file.py") as fpin:
text = fpin.read()
nbook = v3.reads_py(text)
nbook = v4.upgrade(nbook) # Upgrade v3 to v4
jsonform = v4.writes(nbook) + "
"
with open("output-file.ipynb", "w") as fpout:
fpout.write(jsonform)
But not so fast! In fact, the notebook API has a nasty bug: If the last cell in the input is a markdown cell, v3.reads_py()
will lose it. The simplest work-around is to tack on a bogus <markdown>
cell at the end: The bug will delete it, and everyone is happy. So do the following before you pass text
to v3.reads_py()
:
text += """
# <markdowncell>
# If you can read this, reads_py() is no longer broken!
"""
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…