tl;dr
Is there any feature, extension, add-on, or custom function I could use that would extend the autosave functionality in jupyter to automatically maintain a plain text (.py) copy of the code alongside the notebook (.ipynb) file?
additional details
I don't particularly like using Jupyter as an IDE, especially for code that will some day be used in production but a lot of my teammates do. The issue is that we currently don't have any way to automate code saved as a .ipynb file. We also don't have good version control practices in place and I find myself constantly having to remind people to update the "production" copy of the code after they've finished making some changes to the notebook. I'm hoping there might be a way to address this.
CodePudding user response:
You may try to uninstall anaconda and Jupiter. Then install again. it might work.
CodePudding user response:
I was able to find the answer in the 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)
First, create the jupyter_notebook_config.py file under [user directory]/.jupyter if it doesn't already exist. You can generate a template automatically with the command
$ jupyter notebook --generate-config
Next, add the code below:
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
© Copyright 2015, Jupyter Team, https://jupyter.org. Revision 03bc4e9e.