#!/usr/bin/env python # coding: utf-8 # #Using Load, Save and Run Magic (also Writefile) # First lets write some code we want to make into a script file. # In[1]: def fun(): "this is a function" print("hello World") # In[2]: fun() # ##Save # Now let's save it to *test.py*. To do that we need to use the [save magic](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-save) command. In the notebook the format is # # %save filename cell_number # In[3]: get_ipython().run_line_magic('save', 'test.py 1') # _____ # 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. # ##Load # The [load magic](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-load) 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. # In[ ]: # %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. # ##Run # I restarted the kernel here to demonstrate the [run magic](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-run). It allows you to pull code into the current namespace without actually having the code in your notebook. # In[1]: get_ipython().run_line_magic('run', 'test.py') fun() # 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. # ##Writefile # The [writefile cell magic](https://ipython.org/ipython-doc/dev/interactive/magics.html#cellmagic-writefile) is more of a companion to the load magic. Each magic is specific to the current cell. # In[2]: get_ipython().run_cell_magic('writefile', 'test.py', 'def fun():\n "this is a function"\n print("hello World again")\n') # You may notice however there is no prompt abouty overwriting an existing file. # In[3]: get_ipython().run_line_magic('run', 'test.py') fun()