pythonの開発環境でブラウザだけで使えるので最近お世話になっているJupyter notebook, jupyter lab で最終的にpyを出力するのはメニューのexportでやるとして、ipynbからpyファイルを出力してそのpyファイルでバージョン管理をするときに、jupyter_lab_config.py(notebookの場合はjupyter_notebook_config.py)を編集する方法が簡単便利みたいだけど、to_api_pathのところでエラーが出たので、ネットに出ているサンプルを書き換えたメモ
import io
import os
#from notebook.utils import to_api_path #to_api_pathのfromを書き換える
from jupyter_server.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
# https://qiita.com/shiho_h/items/6f1dd3fb1b9136416ec6
if model['last_modified'] - model['created'] < datetime.timedelta(seconds=1):
return # 【追加】createとlast_modifiedの差が小さければ, 新規作成と判断してなにもしない
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
## Python callable or importstring thereof
# See also: ContentsManager.pre_save_hook
# c.FileContentsManager.pre_save_hook = None
def scrub_output_pre_save(model, **kwargs):
"""scrub output before saving notebooks"""
# only run on notebooks
if model['type'] != 'notebook':
return
# only run on nbformat v4
if model['content']['nbformat'] != 4:
return
for cell in model['content']['cells']:
if cell['cell_type'] != 'code':
continue
cell['outputs'] = []
cell['execution_count'] = None
c.FileContentsManager.pre_save_hook = scrub_output_pre_save