簡體   English   中英

自動將jupyter notebook轉成.py

[英]Automatically convert jupyter notebook to .py

我知道有一些關於此的問題,但我還沒有發現任何足夠強大的東西。

目前我從終端使用一個創建.py的命令,然后將它們移動到另一個文件夾:

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

然后,工作流程是在筆記本中編寫代碼,使用git status檢查自上次提交以來發生的變化,創建可能數量巨大的nbconvert命令,然后將它們全部移動。

我想使用!jupyter nbconvert --to script found in this answer之類的東西,但沒有包含 python 文件的單元格出現在 .py 本身中。

因為如果出現該行,我的代碼將永遠無法正常工作。

那么,有沒有正確的方法來處理這個問題呢? 一個可以自動化的,而不是手動復制文件名,創建命令,執行然后重新開始。

另一種方法是使用Jupytext作為 jupyter 安裝的擴展(可以輕松安裝 pip)。

Jupytext 描述(見 github 頁面)

您是否一直希望 Jupyter 筆記本是純文本文檔? 希望您可以在您最喜歡的 IDE 中編輯它們嗎? 並在進行版本控制時獲得清晰而有意義的差異? 那么... Jupytext 很可能是您正在尋找的工具!

它將使配對的筆記本與.py文件保持同步。 然后,您只需要移動.py文件或 gitignore 筆記本,例如作為可能的工作流程。

您可以在筆記本文件的最后一個單元格中添加以下代碼。

!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

Go 到File > Save and Export Notebook as... > Executable Scripts

是我發現的最接近我的想法,但我還沒有嘗試實現它:

   # 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

此外,看起來對 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM