我正在考虑使用*。Ipynb文件作为真相的来源,并以编程方式将它们“编译”为.py文件,用于计划的作业/任务。

我所理解的做到这一点的唯一方法是通过GUI。有没有办法通过命令行来实现?


当前回答

%notebook foo。ipynb magic命令将当前IPython导出到“foo.ipynb”。

更多信息输入%笔记本?

其他回答

遵循前面的例子,但是使用了新的nbformat lib版本:

import nbformat
from nbconvert import PythonExporter

def convertNotebook(notebookPath, modulePath):

  with open(notebookPath) as fh:
    nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)

  exporter = PythonExporter()
  source, meta = exporter.from_notebook_node(nb)

  with open(modulePath, 'w+') as fh:
    fh.writelines(source.encode('utf-8'))

有一个非常好的包叫做nb_dev,它是为在Jupyter notebook中编写Python包而设计的。与nbconvert一样,它可以将笔记本转换为.py文件,但它更灵活、更强大,因为它有许多不错的额外创作功能,可以帮助您在PyPI上开发测试、文档和注册包。它是快速发展起来的。人工智能的人。

它有一点学习曲线,但文档很好,总体上不难。

使用nbconvert 6.07和jupyter client 6.1.12:

转换jupyter笔记本到python脚本

$ jupyter nbconvert mynotebook.ipynb --to python

转换jupyter笔记本到python脚本指定输出文件名

$ jupyter nbconvert mynotebook.ipnb --to python --output myscript.py

下面是一个jq解决方案,可能在某些情况下有用。记住,笔记本只是json。

jq -r '.cells[] | select(.cell_type  == "code") | .source[] | rtrimstr("\n")' $filename

下面的示例将一个名为a_notebook的Iron Python Notebook转换为。ipynb转换到一个名为a_python_script.py的python脚本中,省略带有关键字remove的单元格,我手动将其添加到我不想在脚本中结束的单元格中,省略了可视化和其他步骤,一旦我完成了笔记本,我不需要由脚本执行。

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', encoding='utf-8') as f:
    f.writelines(the_python_script)