- How to load/edit/run/save text files (.py) into an IPython notebook cell?
- 6 Answers 6
- How To Run Python Script .py File In Jupyter Notebook .ipynb File And IPython
- 1. Invoke Python Script File From Jupyter Notebook.
- 2. Invoke Python Script File From Ipython Command-Line.
- How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?
- 5 Answers 5
- Folyamatosan induló kurzusaink
- Tanulj online
- Interaktív feladatok
- Előképzettség nélkül
- Örökös hozzáférés
- Tapasztalt mentorok
- Pénzvisszafizetési garancia
How to load/edit/run/save text files (.py) into an IPython notebook cell?
I’ve recently moved over to using IPython notebooks as part of my workflow. However, I’ve not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done? I’ve found this in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve. Any suggestions would be much appreciated.
Good question. I have yet to see a really satisfying answer. It’s especially important when serving an IPython notebook over the internet. If people want to see/edit the source code of functions that are imported (with syntax highlighting, etc) there’s currently no easy way to do it. It should be possible to just open py files without transforming them into ipynb files.
6 Answers 6
EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.
A text file can be loaded in a notebook cell with the magic command %load .
If you execute a cell containing:
the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.
To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.
To see the help for any magic command add a ? : like %load? or %%writefile? .
For general help on magic functions type «%magic» For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. ‘%cd?’.
See also: Magic functions from the official IPython docs.
How To Run Python Script .py File In Jupyter Notebook .ipynb File And IPython
In this article, I will tell you how to invoke a python script file (.py) from the Jupyter notebook file (.ipynb) and ipython console. But first, you should create a python virtual environment in Anaconda and start Jupyter notebook server, you can read the article How To Start Jupyter Notebook In Anaconda Python Virtual Environment to learn more.
1. Invoke Python Script File From Jupyter Notebook.
- Create a jupyter notebook file with the name InvokePythonScript.ipynb. ( There are also 2 python script files list_file.py and list_file_path.py which we will introduce later. )
- Click file InvokePythonScript.ipynb to edit it.
- Add the first line cell and input below source code. Below ipython code will create a python script file with name list_file.py. When you run this python script file in jupyter notebook, it will print out all the files and directories’ names in the folder which you pass to it as a command-line input argument. If you do not pass any folder name as the command line input arguments when you invoke list_file.py, it will list the files and directories’ names in the current directory.
%%writefile list_file.py # use ipython magic command %%writefile to create a python script file and write below script content to it. # import two python standard module. import sys import os # set dir_name value to current directory by default. dir_name = './' # if user input an argument. if len(sys.argv) > 1: # give the first argument value to a local variable, the argument value should be a directory name. dir_name = sys.argv[1] # get all the dir_name directory contained files in a list files_list = os.listdir(dir_name) # loop in the files_list. for file in files_list: # print out file name in the standard output. print(file)
%run -i list_file.py .ipynb_checkpoints InvokePythonScript.ipynb list_file.py list_file_path.py
# import system module. import sys import os # set dir_name's value to current folder by default. dir_name = './' # if invoke this scrpit with more than 1 argument. if len(sys.argv) > 1: i = 1 # loop for all the args passed when this .py file is invoked. for arg in sys.argv: print('arg',i,'=',arg) i = i + 1 # assign the first argument value to local variable dir_name. dir_name = sys.argv[1] # list all the files in the dir_name directory and return them in a list. files_list = os.listdir(dir_name) # loop in above files_list for file in files_list: # print out each file absolute path. print(os.path.abspath(file))
%run list_file_path.py ./ arg 1 = list_file_path.py arg 2 = ./ C:\WorkSpace\.ipynb_checkpoints C:\WorkSpace\InvokePythonScript.ipynb C:\WorkSpace\list_file.py C:\WorkSpace\list_file_path.py
2. Invoke Python Script File From Ipython Command-Line.
- Click the green triangle button of the python virtual environment in the Anaconda environments list, then click the Open Terminal menu item.
- Then go to the python script file saved directory use cd command, and then run command ipython -i list_file.py like below. It will print out all files and folders name in the current folder.
(env_jupyter_example) C:\Users\song zhao>cd C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample (env_jupyter_example) C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample>DIR Volume in drive C has no label. Volume Serial Number is E6EE-6486 Directory of C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample 07/25/2020 09:48 PM . 07/25/2020 09:48 PM .. 07/25/2020 09:06 PM .ipynb_checkpoints 07/25/2020 09:48 PM 2,682 InvokePythonScript.ipynb 07/25/2020 09:47 PM 665 list_file.py 07/21/2020 09:31 AM 708 list_file_path.py 3 File(s) 4,055 bytes 3 Dir(s) 69,612,453,888 bytes free (env_jupyter_example) C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample>ipython -i list_file.py Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help. .ipynb_checkpoints InvokePythonScript.ipynb list_file.py list_file_path.py In [1]: exit() (env_jupyter_example) C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample>
How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?
I am working on a Python Notebook and I would like that large input code [input] pack into a [* .PY] files and call this files from the notebook. The action of running a [.PY] file from the Notebook is known to me and the command varies between Linux or Windows. But when I do this action and execute the [.PY] file from the notebook, it does not recognize any existing library or variable loaded in the notebook (it’s like the [.PY] file start from zero. ). Is there any way to fix this? A possible simplified example of the problem would be the following:
In[1]: import numpy as np import matplotlib.pyplot as plt In[2]: def f(x): return np.exp(-x ** 2) In[3]: x = np.linspace(-1, 3, 100) In[4]: %run script.py
plt.plot(x, f(x)) plt.xlabel("Eje $x$",fontsize=16) plt.ylabel("$f(x)$",fontsize=16) plt.title("Funcion $f(x)$")
Your x variable is local to your .ipynb file, not your .py file. The .py file has no idea about x . Find a way to pass that value between scripts. Something like from myfile.ipynb import x (don’t know if you can do that type of import with .ipynb files, but do you see what I mean?
5 Answers 5
-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.
Therefore, supplying -i does the trick:
The «correct» way to do it
Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don’t know how a more pythonic way would look like.
The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).
I’d like to show you how to do it without actually having to execute the other file over and over again.
Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
If you’re constantly editing the other file, then autoreload comes to your help.
Your example would look like this:
script.py
import matplotlib.pyplot as plt def myplot(f, x): """ :param f: function to plot :type f: callable :param x: values for x :type x: list or ndarray Plots the function f(x). """ # yes, you can pass functions around as if # they were ordinary variables (they are) plt.plot(x, f(x)) plt.xlabel("Eje $x$",fontsize=16) plt.ylabel("$f(x)$",fontsize=16) plt.title("Funcion $f(x)$")
Jupyter console
In [1]: import numpy as np In [2]: %load_ext autoreload In [3]: %autoreload 1 In [4]: %aimport script In [5]: def f(x): : return np.exp(-x ** 2) : : In [6]: x = np.linspace(-1, 3, 100) In [7]: script.myplot(f, x) In [8]: ?script.myplot Signature: script.myplot(f, x) Docstring: :param f: function to plot :type f: callable :param x: x values :type x: list or ndarray File: [. ]\script.py Type: function
Folyamatosan induló kurzusaink
A CodeBerry megtanít a legmodernebb technológiák használatára, és megadja neked a szükséges tudást és eszközöket ahhoz, hogy fejlesztőként dolgozhass.
Készen állsz a tanulásra? Csatlakozz te is a 160 000 programozást tanuló diákunk csapatához!
Tanulj online
Tanulhatsz otthon, a szünetekben, vagy a kedvenc kávézódban.
Interaktív feladatok
A tudásszintedtől függetlenül több, mint 100 órányi szórakoztató feladatsor vár.
Előképzettség nélkül
Teljesen kezdőként is belevághatsz a kurzusokba, semmilyen programozási ismeretre nincs hozzá szükséged.
Örökös hozzáférés
A kurzusok elvégzése után is bármikor hozzáférhetsz a leckékhez, hogy ismételhess és gyakorolhass, ami a programozás tanulásánál különösen fontos.
Tapasztalt mentorok
A CodeBerry tanárai több év programozói tapasztalattal rendelkező szakemberek, akikre mindig számíthatsz, ha segítségre van szükséged a tanulás folyamán.
Pénzvisszafizetési garancia
Ha nem vagy elégedett a szolgáltatásunkkal, a vásárlástól számított 14 napon belül kérdés nélkül visszaadjuk a pénzed.