Auto export python code from jupyter lab

because it is easier to search from .py files in text format. Using nbautoexports in jupyter lab
jupyter
Published

July 21, 2022

This hack comes from EASIER CODE REVIEWS FOR JUPYTER NOTEBOOKS WITH NBAUTOEXPORT.

And this is an updated version for Jupyter lab when Auto export python code from jupyter notebooks was specifically for Jupyter notebook.

Install NBAUTOEXPORT

You should install it in the same virtual environment that you are running Jupyter Notebook or JupyterLab from.

# in base (from in _conda_env/base.txt)
pip install nbautoexport
!cat ~/_conda_env/base.txt
conda install -y mamba -n base -c conda-forge
mamba init
mamba install -y nb_conda_kernels
mamba install -y -c conda-forge jupyterlab jupyterlab-git
mamba install -y ipywidgets

mamba install -y -c conda-forge jupyterlab_execute_time
#and change in jupyter lab : Settings- > Advanced Settings Editor -> Notebook: {"recordTiming": true} 

pip install --upgrade nvitop

jupyter labextension install jupyterlab-spreadsheet
pip install jupyterlab-tabular-data-editor
pip install nbautoexport

There are two main steps to setting up nbautoexport:

  • Install nbautoexport as a post-save hook with Jupyter (once per machine you use it on)
  • Configure a notebooks directory (once per project you are working on)

Install nbautoexport as a post-save hook

# from base environment
nbautoexport install

> nbautoexport post-save hook successfully installed with Jupyter.
> If a Jupyter server is already running, you will need to restart it for nbautoexport to work.

Configure a notebooks directory

# from your notebooks directory
nbautoexport configure .

It creates this file .nbautoexport

───────┬───────────────────────────────────────────────────────────
        File: .nbautoexport
───────┼───────────────────────────────────────────────────────────
   1   │ {
   2"export_formats": [
   3"script"
   4   │   ],
   5"organize_by": "extension",
   6"clean": {
   7"exclude": []
   8   │   }
   9   │ }
───────┴───────────────────────────────────────────────────────────

Test

After running it in my blog _notebooks directory, and saving a notebook; a script directory and .py file with notebook content are created

(base) guillaume@LL11LPC0PQARQ:~/git/guillaume_blog/_notebooks$ tree
.
├── .nbautoexport
├── 2022-07-21-jupyter-export-lab-as-py.ipynb
├── README.md
└── script
    └── 2022-07-21-jupyter-export-lab-as-py.py

2022-07-21-jupyter-export-lab-as-py.py has been created as expected

I can now delete .nbautoexport and it won’t happen in that directory