How do I convert a IPython Notebook into a Python file via commandline?

后端 未结 10 2519
一生所求
一生所求 2020-11-29 14:42

I\'m looking at using the *.ipynb files as the source of truth and programmatically \'compiling\' them into .py files for scheduled jobs/tasks.

The

10条回答
  •  有刺的猬
    2020-11-29 15:00

    You can do this from the IPython API.

    from IPython.nbformat import current as nbformat
    from IPython.nbconvert import PythonExporter
    
    filepath = 'path/to/my_notebook.ipynb'
    export_path = 'path/to/my_notebook.py'
    
    with open(filepath) as fh:
        nb = nbformat.reads_json(fh.read())
    
    exporter = PythonExporter()
    
    # source is a tuple of python source code
    # meta contains metadata
    source, meta = exporter.from_notebook_node(nb)
    
    with open(export_path, 'w+') as fh:
        fh.writelines(source)
    

提交回复
热议问题