ipython notebook --script已弃用.如何用post save hook替换?

lou*_*uic 15 hook ipython-notebook jupyter

我一直在使用"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`.
Run Code Online (Sandbox Code Playgroud)

据我所知,我需要设置一个后保存挂钩,但我不明白该怎么做.谁能解释一下?

Tri*_*eid 19

[@mobius饺子的评论更新]

找到您的配置文件:

Jupyter/ipython> = 4.0

jupyter --config-dir
Run Code Online (Sandbox Code Playgroud)

ipython <4.0

ipython locate profile default
Run Code Online (Sandbox Code Playgroud)

如果您需要新配置:

Jupyter/ipython> = 4.0

jupyter notebook --generate-config
Run Code Online (Sandbox Code Playgroud)

ipython <4.0

ipython profile create
Run Code Online (Sandbox Code Playgroud)

在这个目录中,会有一个名为的文件[jupyter | ipython]_notebook_config.py,将以下代码放在该文件中的ipython的GitHub问题页面中:

import os
from subprocess import check_call

c = get_config()

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)

c.FileContentsManager.post_save_hook = post_save
Run Code Online (Sandbox Code Playgroud)

对于Jupyter,更换ipythonjupyter的check_call.

请注意,有一个相应的"预保存"钩子,并且您可以调用任何子进程或在那里运行任意代码...如果您想做任何事情,比如先检查一些条件,通知API消费者,或添加一个git提交已保存的脚本.

干杯,

-t.

  • **更新:**这个解决方案在iPython版本4中被破解,因为来自iPython的Jupyter的"大分裂".要将此解决方案调整为版本4,请使用命令`jupyter notebook --generate-config`来创建配置文件.命令`jupyter --config-dir`找出包含配置文件的目录.并且@TristanReid给出的代码片段应该添加到名为`jupyter_notebook_config.py`的文件中.其余的工作和以前一样. (3认同)