IPython Magic Functions (%run vs. %load vs. %%writefile):
- With Jupyter notebooks, you can reuse code that you’ve developed elsewhere, say, in a code editor. There are a few different ways you can access that code from within a notebook.
- The %load IPython magic function allows you to load code from a file into a cell in a Jupyter notebook.
- For example, in an empty code cell, you can type %load filename.py, where filename.py is the name of the file you want to load.
- This loads the code into the cell, but does not yet run it. It does exactly the same thing as if you had typed that code into the cell directly. Once it’s loaded, click on the cell with the loaded code to make that cell active, and enter Shift+Enter to execute it.
- Once the cell has been executed, we can then enter and execute %whos in an empty cell to see has been defined.
- For example, in an empty code cell, you can type %load filename.py, where filename.py is the name of the file you want to load.
- The %run IPython magic function alternatively just executes the code in a specified Python file without showing you the code in the notebook.
- The %%writefile cell magic function allows you to write the contents of a cell to a file. For example, if you have a cell with some code in it, you can use %%writefile filename.py at the top of the cell to write that code to a file named filename.py. This is useful for saving code you’ve written in a notebook to a separate file for later use.
Summary:
-
In summary, it is often the case that you’ve written Python code in an editor, and then you want to bring it into a notebook in order to use it in a particular analysis. There are different methods for bringing that code into a notebook, each more appropriate for different purposes. While not rigid guidelines, the following tips can be useful in your decisions about which method to use:1
-
Loading Python code into a notebook using %load is useful if:
- you want to display the code itself within the notebook (for example, to document what you’ve done)
- you want to bring some previously written code into the notebook and make some modifications to it
-
Running Python code in a notebook using %run is useful if:
- you just want to execute everything in that file without showing all the code, so that you can access all the objects defined in the file
-
Importing Python code into a notebook using import is useful if:
- you want to keep control of module namespaces so that names in different modules do not conflict
- you want to import more than one module to get functions you have written, and to combine calls to those functions within the notebook to carry out your data analysis
Footnotes
-
Chris Myers, Senior Research Associate and Adjunct Professor, Center for Advanced Computing, Cornell University. ↩