First lets write some code we want to make into a script file.
def fun():
"this is a function"
print("hello World")
fun()
hello World
Now let's save it to test.py. To do that we need to use the save magic command. In the notebook the format is
%save filename cell_number
%save test.py 1
File `test.py` exists. Overwrite (y/[N])? y The following commands were written to file `test.py`: def fun(): "this is a function" print("hello World")
The output you see above is an automatic report about the results of using save. The prompt you see about overwriting is due to this being the second time I ran this notebook.
The load magic allows you to bring in code to your current notebook for editing or execution. You can load an entire file, just specific lines or individual functions from it. Further more you can not only pull code from your local hard drive but also online locations via url.
Below is the results of typing
%load test.py
and pressing Ctrl-Enter.
# %load test.py
def fun():
"this is a function"
print("hello World")
Notice there is not cell number indicating that that cell has not been executed. Also the magic command is now commented out to prevent accidental repeated execution.
I restarted the kernel here to demonstrate the run magic. It allows you to pull code into the current namespace without actually having the code in your notebook.
%run test.py
fun()
hello World again
By populating your current namespace run is much like the import command. However, unlike when you use import if modifications are made to the code that you brought in using run you do not have to use a different command (like reload) to update your namespace, you just need to execute run again and you are current.
These three commands make developing code libraries in IPython relatively easy. You can now write and test code in your notebook, save it to disk and use it in other notebooks. This is particularly useful when the point of the notebook is not to share code but rather the results.
The writefile cell magic is more of a companion to the load magic. Each magic is specific to the current cell.
%%writefile test.py
def fun():
"this is a function"
print("hello World again")
Overwriting test.py
You may notice however there is no prompt abouty overwriting an existing file.
%run test.py
fun()
hello World again