Converting to (not from) ipython Notebook format

后端 未结 10 996
刺人心
刺人心 2020-11-29 17:10

IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already ha

10条回答
  •  生来不讨喜
    2020-11-29 17:39

    The following works for IPython 3, but not IPython 4.

    The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py into a notebook test.ipynb.

    import IPython.nbformat.current as nbf
    nb = nbf.read(open('test.py', 'r'), 'py')
    nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')
    

    Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):

    https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py

    Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py from the IPython 3.2.1 release:

    https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py

    Basically you use special comments such as # or # to separate the individual cells. Look at the line.startswith statements in PyReader.to_notebook for a complete list.

提交回复
热议问题