我正在考虑使用*。Ipynb文件作为真相的来源,并以编程方式将它们“编译”为.py文件,用于计划的作业/任务。
我所理解的做到这一点的唯一方法是通过GUI。有没有办法通过命令行来实现?
我正在考虑使用*。Ipynb文件作为真相的来源,并以编程方式将它们“编译”为.py文件,用于计划的作业/任务。
我所理解的做到这一点的唯一方法是通过GUI。有没有办法通过命令行来实现?
当前回答
我发现有两种方法可以用命令行将Jupyter Notebook转换为普通的Python脚本。下面是Jupyter笔记本的示例和两个工具的输出。
1. 使用nbconvert
nbconvert是在Jupyter Notebook用户界面下载中作为功能使用的工具。它可以用作命令行工具:
jupyter nbconvert --to python notebook.ipynb
Python脚本示例:
2. 使用jupytext
jupytext是一个保持.ipynb文件与.py文件同步的包。它还可以用于在命令行中转换.ipynb文件。它支持几种类型的转换:
转换为轻格式的Python脚本
jupytext --to py notebook.ipynb
python脚本示例:
转换为百分比格式的Python脚本
jupytext --to py:percent notebook.ipynb
Python脚本示例:
其他回答
如果你想转换所有*。Ipynb文件从当前目录转移到python脚本,可以运行如下命令:
jupyter nbconvert --to script *.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'))
下面是一种不使用ipython就可以从V3或V4 ipynb中提取代码的快速而简单的方法。它不检查单元格类型等。
import sys,json
f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w') #output.py
if j["nbformat"] >=4:
for i,cell in enumerate(j["cells"]):
of.write("#cell "+str(i)+"\n")
for line in cell["source"]:
of.write(line)
of.write('\n\n')
else:
for i,cell in enumerate(j["worksheets"][0]["cells"]):
of.write("#cell "+str(i)+"\n")
for line in cell["input"]:
of.write(line)
of.write('\n\n')
of.close()
没有文件/目录错误
在我的mint [ubuntu]系统上,尽管已经安装了jupyter,笔记本电脑也可以工作,但jupyter nbconvert——to脚本给出了错误,没有文件/目录,直到我做了一个单独的
sudo apt-get install jupyter-nbconvert
然后一切都很顺利。我只是想添加这个,以防有人碰到同样的错误(对我来说,这是令人困惑的,因为我认为没有文件错误指向笔记本,它肯定在本地目录中,我花了一段时间才意识到子命令没有安装)。
下面的示例将一个名为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)