1. I automatically write my notebooks as a .py file every time I save them in jupyter. To do this you have to create a jupyter_notebook_config.py file with the contents below and put it into your ~/.jupyter folder
2. I add the folder where I save .py files into sys.path using the following lines in my ~/.ipython/profile_default/ipython_config.py file.
Don’t forget to add an empty __init__.py file to the directory you want to use as the root for your packages
c.InteractiveShellApp.exec_lines = ['import sys; import os; home = os.path.expanduser("~"); sys.path.append(home + “[folder name]");’] # replace folder name with your root folder for packages
# Based off
https://github.com/jupyter/notebook/blob/master/docs/source/extending/savehooks.rstimport io
import os
from notebook.utils import to_api_path
def script_post_save(model, os_path, contents_manager, **kwargs):
"""convert notebooks to Python script after save with nbconvert
replaces `ipython notebook --script`
"""
log = contents_manager.log
# save .py file
base, ext = os.path.splitext(os_path)
import sys,json
f = open(os_path, 'r') #input.ipynb
j = json.load(f)
output_fname = base + '.py'
log.info("Saving script /%s", to_api_path(output_fname, contents_manager.root_dir))
of = open(output_fname, 'w') #output.py
for i,cell in enumerate(j["cells"]):
if cell["cell_type"] != "code": continue
of.write("#cell "+str(i)+"\n")
for line in cell["source"]:
of.write(line)
of.write('\n\n')
of.close()
if os.path.isfile(base + '.pyc'):
os.remove(base + '.pyc')
log.info("Done saving script /%s", to_api_path(output_fname, contents_manager.root_dir))
c.FileContentsManager.post_save_hook = script_post_save