A2oz

How do I run a Jupyter Notebook from another Jupyter Notebook?

Published in Jupyter Notebook 2 mins read

You can run a Jupyter Notebook from another Jupyter Notebook using the %run magic command. This command executes the code in the specified notebook in the current kernel.

Using the %run magic command:

  1. Open the notebook that you want to run from another notebook.
  2. In the cell where you want to run the other notebook, type:
    %run ./path/to/notebook.ipynb
    • Replace ./path/to/notebook.ipynb with the actual path to the notebook you want to execute.
  3. Run the cell. This will execute all the cells in the specified notebook.

Practical insights:

  • Importing functions: If you only want to import specific functions or variables from another notebook, you can use the %load magic command to import the code into the current notebook.
  • Sharing variables: You can also use the %store magic command to share variables between notebooks.
  • Creating modules: For larger projects, consider creating Python modules for your code and importing them into your notebooks.

Example:

Let's say you have two notebooks: notebook1.ipynb and notebook2.ipynb. You want to run notebook2.ipynb from notebook1.ipynb.

In notebook1.ipynb, you can add a cell with the following code:

%run ./notebook2.ipynb

When you run this cell, all the code in notebook2.ipynb will be executed.

Related Articles