tl;dr
我可以使用任何功能、扩展、附加组件或自定义函数来扩展 Jupyter 中的自动保存功能,以自动维护笔记本 (.ipynb) 文件旁边的纯文本 (.py) 代码副本?
其他详细信息
我不是特别喜欢将 Jupyter 用作 IDE,尤其是对于有一天会在生产中使用的代码,但我的很多队友都这样做。问题是我们目前没有任何方法可以自动保存为 .ipynb 文件的代码。我们也没有适当的版本控制实践,我发现自己不得不不断提醒人们在完成对笔记本的一些更改后更新代码的“生产”副本。我希望有办法解决这个问题。
最佳答案
我能够在 Jupyter Notebook documentation 中找到答案
File save hooks
You can configure functions that are run whenever a file is saved. There are two hooks available:
ContentsManager.pre_save_hook runs on the API path and model with content. This can be used for things like stripping output that people don’t like adding to VCS noise.
FileContentsManager.post_save_hook runs on the filesystem path and model without content. This could be used to commit changes after every save, for instance.
They are both called with keyword arguments:
> pre_save_hook(model=model, path=path, contents_manager=cm)
> post_save_hook(model=model, os_path=os_path, contents_manager=cm)
首先,如果 jupyter_notebook_config.py 文件不存在,请在 [用户目录]/.jupyter 下创建它。您可以使用命令自动生成模板
$ jupyter notebook --generate-config
接下来,添加下面的代码:
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
© 版权所有 2015,Jupyter 团队,https://jupyter.org .修订版 03bc4e9e。
https://stackoverflow.com/questions/69322473/
相关文章:
node.js - SassError : Can't find stylesheet to imp
google-cloud-platform - 将 PHP crypt MD5 密码导入 Googl
javascript - new Array(n).fill ('apple' ) 在 JavaSc
python - 如何删除 Pandas 中包含特定字符串的任何行?
swiftui - 如何在 iOS 15 中使用 SwiftUI 在特定 View 中隐藏 TabB
html - 使用 CSS 将文本颜色设置为红色背景上的白色和白色背景上的黑色文本颜色