自动将Jupyter Notebook转换为 .py文件

6

我知道有一些关于这个问题的问题,但我没有找到足够健壮的任何东西。

目前我正在使用一个从终端启动的命令创建 .py 文件,然后将它们移动到另一个文件夹:

jupyter nbconvert --to script '/folder/notebooks/notebook.ipynb' &&  \
mv ./folder/notebooks/*.py ./folder/python_scripts && \

工作流程是在notebook中编写代码,使用git status检查自上次提交以来更改了什么,创建大量的nbconvert命令,然后将它们全部移动。

我想使用类似!jupyter nbconvert --to script的东西,可以在这个答案中找到,但是不希望在生成.py文件时出现创建python文件的单元格。

因为如果这行代码出现了,我的代码就永远无法正常工作。

那么,有没有适当的方法来解决这个问题?一种可以自动化处理的方法,而不是手动复制文件名,创建命令,执行,然后再重新开始。

4个回答

4
另一种方法是将Jupytext用作jupyter安装的扩展程序(可以轻松使用pip进行安装)。 (请参见github页面)
您是否一直希望Jupyter笔记本是纯文本文档? 希望您可以在喜欢的IDE中编辑它们?并且在进行版本控制时获得清晰和有意义的差异?那么... Jupytext可能是您正在寻找的工具!
它将使配对的笔记本与.py文件保持同步。 然后,您只需要移动您的.py文件或gitignore笔记本,例如可能的工作流程。

请考虑详细说明您的链接参考。 - sao
非常有帮助的答案。谢谢。 - nonbeing

4
你可以将以下代码添加到笔记本文件的最后一个单元格中。
!jupyter nbconvert --to script mycode.ipynb
with open('mycode.py', 'r') as f:
    lines = f.readlines()
with open('mycode.py', 'w') as f:
    for line in lines:
        if 'nbconvert --to script' in line:
            break
        else:
            f.write(line)

它将生成 .py 文件,然后从其中删除此代码。您最终将获得一个干净的脚本,它将不再调用 !jupyter nbconvert

我看到过类似的解决方案,但我对这种方法的问题在于如何避免它出现在脚本中?也就是说,想法是自动执行.py文件。那么,.py文件仍然会有这段代码,对吧?如果是这样的话,对于我的自动化目的来说,它不会起作用。 - monkey intern
1
不,py文件中不会有这段代码。你可以试试看。 - alec_djinn
if语句中是否有错别字? - mLstudent33
@mLstudent33 哪里错别字了? - alec_djinn
实际上它只是看起来变灰了,但它并不是一个注释,对吧?在S.O.上使用nbconvert --to script命令时,两个破折号可能会让它变灰,认为它是一个注释。 - mLstudent33
是的,这是一个字符串,我不知道为什么没有正确着色。 - alec_djinn

1

前往 文件 > 另存为可执行脚本


1
我猜测用户界面是版本特定的。我的路径是:文件 > 另存为... > Python (.py) - Julia Meshcheryakova

0

是我找到的最接近我所想要的,但我还没有尝试实现它:

   # A post-save hook to make a script equivalent whenever the notebook is saved (replacing the --script option in older versions of the notebook):

import io
import os
from notebook.utils import to_api_path

_script_exporter = None

def script_post_save(model, os_path, contents_manager, **kwargs):
    """convert notebooks to Python script after save with nbconvert

    replaces `jupyter notebook --script`
    """
    from nbconvert.exporters.script import ScriptExporter

    if model['type'] != 'notebook':
        return

    global _script_exporter

    if _script_exporter is None:
        _script_exporter = ScriptExporter(parent=contents_manager)

    log = contents_manager.log

    base, ext = os.path.splitext(os_path)
    script, resources = _script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')
    log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir))

    with io.open(script_fname, 'w', encoding='utf-8') as f:
        f.write(script)

c.FileContentsManager.post_save_hook = script_post_save

此外,this 看起来已经在 GitHub 上为一些用户工作了,因此我在这里提供参考:

import os
from subprocess import check_call

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py scripts"""
    if model['type'] != 'notebook':
        return # only do this for notebooks
    d, fname = os.path.split(os_path)
    check_call(['ipython', 'nbconvert', '--to', 'script', fname], cwd=d)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接