Converting to (not from) ipython Notebook format

后端 未结 10 994
刺人心
刺人心 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:32

    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 lines anywhere in the file.)

    # -*- coding: utf-8 -*-
    # 3.0
    
    # 
    
    # 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!
    
    # 
    
    print("Hello, IPython")
    
    # 
    
    # Raw cell contents are not formatted as markdown
    

    (The API also accepts the obsolete directives and , 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) + "\n"
    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 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 += """
    # 
    
    # If you can read this, reads_py() is no longer broken! 
    """
    

提交回复
热议问题