I am using Jupyter notebook. In the same folder in which the notebook is running, I have a function f defined as
def f(x):
return x**2
I have saved this function as f.py in the same folder. Now I want to call this function in the notebook that is running. How do I do that? If the function was typed into the notebook, I could have just typed
f(4)
py file), or Jupyter Notebook. Remember the file that contains the function definitions and the file calling the functions must be in the same directory. To use the functions written in one file inside another file include the import line, from filename import function_name .
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.
%run f.py
load
magic was just copying the whole file into a cell, which was not what i need. Neither did the importing worked for me. was throwing some weird errors. So i ended up using the run
magic.
Try the load
magic;
%load f.py
That automatically loads the in the entire contents of file so that you can edit it in a cell.
from f import f
Is another option.
If neither one of those work for you could try adding your notebook's directory to the the system path by running this block as a cell before trying to call your function;
import os
import sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
sys.path.append(nb_dir)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With