Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run an existing function from Jupyter notebook

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)
like image 253
python_tensorflow Avatar asked Aug 22 '17 02:08

python_tensorflow


People also ask

Can you call functions from other Jupyter notebooks?

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 .

How do I run an existing Python file in Jupyter?

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.


2 Answers

%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.

like image 169
Nithin Avatar answered Oct 09 '22 21:10

Nithin


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)
like image 43
James Draper Avatar answered Oct 09 '22 20:10

James Draper