Valentin Fabianski
Valentin Fabianski

Reputation: 706

Running a Jupyter notebook from another notebook

I wonder if it is possible to run a *.ipynb file from another *.ipynb file and get a returned value. I know that we can run like this:

%run ./called_notebook.ipynb

the called_notebook contains:

def foo():
    print(1)
    return 2
foo()

But it only prints "1" without giving me the opportunity to handle the returned value. Is it even possible ? Does the following kind of code even exist :

a = %run ./called_notebook.ipynb

?

Thanks !

Upvotes: 57

Views: 63398

Answers (3)

Cristian Quintero
Cristian Quintero

Reputation: 11

Have you tried the magic tag "%store <variable?" and "%store -r "? It is a way to store data in the iPython storing space, and you may share variables in runtime whether the notebooks are run in the same iPython instance.

Upvotes: 0

user-asterix
user-asterix

Reputation: 936

Matt's Answer works. However I wanted to run from calling_notebook.ipynb the other called_notebook.ipynb and transfer data frame from called_notebook to calling_notebook WITHOUT displaying any of the output.

I tried many options all did not work (tags etc). However this below worked (suppressed all output in called_notebook.ipynb).

    # to suppress output of the cell
    %%capture        
    %run -n ./called_notebook.ipynb  
    df = DFF()       # function in called_notebook that returns a dataframe after doing all work
    df.info()  

Upvotes: 2

Matt
Matt

Reputation: 6320

I'd suggest running the foo function from the new notebook. In other words:

%run ./called_notebook.ipynb
foo()

In my opinion, this is best practices for using the %run magic command. Store your high level APIs in a separate notebook (such as foo), but keep your function calls visible in the master notebook.

Upvotes: 77

Related Questions