DayG
DayG

Reputation: 41

How to add same lines of code at the beginning of each cell in a Jupyter Notebook?

I would like to push my notebooks into GitLab without them showing the different outputs (3d plots, dataframes, etc...) in order to keep the size of those notebooks reasonable.

I had the following idea: setting up a boolean variable at the beginning of the notebook that when set to True, the %%capture cell-magic command would activate in every cell it is in.

import various libraries
## Setting the boolean variable to True:
do_not_show = True
## This cell would not display anything
if do_not_show:
    %%capture

plt.plot(...)
plt.savefig(...)

So, is there a way to write the if statement (or more generally, any lines of code) at the beginning of each existing cell of a notebook? Moreover, would there be a way to automatically write those lines of code automatically when creating a new cell?

Adding the if statement in each required cell is quite tedious for long notebooks...

Upvotes: 1

Views: 894

Answers (1)

MrX
MrX

Reputation: 27

Yes, it is possible to add the same lines of code at the beginning of each cell in a Jupyter Notebook using a Jupyter Notebook extension called 'pre' and 'post'.

Here are the steps to achieve this:

  1. Install the 'jupyter_contrib_nbextensions' package by running the following command in your terminal:

    !pip install jupyter_contrib_nbextensions
    
    
  2. Enable the 'pre' and 'post' extensions by running the following commands in your terminal:

jupyter contrib nbextension install --user
jupyter nbextension enable codefolding/main
  1. Open the Jupyter Notebook in which you want to add the lines of code.

  2. Click on the 'Edit' menu and select 'nbextensions config'.

  3. Scroll down to the 'Codefolding' section and enable the 'Collapsible Headings' option.

  4. Close the 'nbextensions config' tab and refresh the notebook.

  5. Now you can add the lines of code that you want to be executed at the beginning of each cell in a markdown cell at the beginning of the notebook, with the prefix '%%javascript'.

For example, you can add the following code to the beginning of the notebook:

%%javascript
var kernel = Jupyter.notebook.kernel;
kernel.execute('do_not_show = True');
kernel.execute('%%capture');

This will set the 'do_not_show' variable to 'True' and activate the '%%capture' cell-magic command in every cell.

  1. Save the notebook and close it.
  2. Reopen the notebook to check if the changes were applied.

Note that this solution will only work for existing cells in the notebook, so if you want to automatically add the same lines of code to new cells as well, you will need to use a different approach such as creating a custom Jupyter Notebook template or using a script to automatically modify the notebook.

Upvotes: 0

Related Questions