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

后端 未结 10 2584
一生所求
一生所求 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 14:57

    The following example turns an Iron Python Notebook called a_notebook.ipynb into a python script called a_python_script.py leaving out the cells tagged with the keyword remove, which I add manually to the cells that I don't want to end up in the script, leaving out visualizations and other steps that once I am done with the notebook I don't need to be executed by the script.

    import nbformat as nbf
    from nbconvert.exporters import PythonExporter
    from nbconvert.preprocessors import TagRemovePreprocessor
    
    with open("a_notebook.ipynb", 'r', encoding='utf-8') as f:
        the_notebook_nodes = nbf.read(f, as_version = 4)
    
    trp = TagRemovePreprocessor()
    
    trp.remove_cell_tags = ("remove",)
    
    pexp = PythonExporter()
    
    pexp.register_preprocessor(trp, enabled= True)
    
    the_python_script, meta = pexp.from_notebook_node(the_notebook_nodes)
    
    with open("a_python_script.py", 'w') as f:
        f.writelines(the_python_script)
    

提交回复
热议问题