18

「ipython --script」を使用して、各 ipython ノートブックの .py ファイルを自動的に保存しているので、それを使用してクラスを他のノートブックにインポートできます。しかし、これは最近機能しなくなり、次のエラーメッセージが表示されます。

`--script` is deprecated. You can trigger nbconvert via pre- or post-save hooks:
ContentsManager.pre_save_hook
FileContentsManager.post_save_hook
A post-save hook has been registered that calls:
ipython nbconvert --to script [notebook]
which behaves similarly to `--script`.

これを理解しているので、保存後のフックを設定する必要がありますが、これを行う方法がわかりません。誰か説明できますか?

4

3 に答える 3

2

これは、新しいスレッドを呼び出さない別のアプローチです ( を使用check_call)。jupyter_notebook_config.pyトリスタンの回答のように、次を追加します。

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 `ipython 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)
    py_fname = base + '.py'
    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

免責事項: 私はどこかでこれを入手したと確信していますが、今は見つかりません。ここに置くと、後で見つけやすくなります (:

于 2016-11-17T17:08:11.073 に答える