8

From a jupyter notebook, I'd like to call a function written in another .ipynb file. The partial answer is given in this thread Reusing code from different IPython notebooks by drevicko. As an example, I'm using plus_one function written in plus_one.ipynb:

def plus_one(x):
    print(x + 1)

Then, in my current notebook, I execute the cell:

%run plus_one.ipynb 3

which gives me no output. My expected output is 4. How to pass an argument (3) to this script? Thanks!

koch
  • 97
  • 1
  • 6

1 Answers1

8

From the %run? documentation

This is similar to running at a system prompt python file args, but with the advantage of giving you IPython's tracebacks, and of loading all variables into your interactive namespace for further use

so all the cells from plus_one.ipynb are run and all it's variables are added to the namespace of the calling notebook. This does not call the plus_one method directly (unless it is called in the other notebook), but it defines it in the current namespace, kind of like an import in a regular python script.so from that moment on, you should be able to do plus_one(3) in the calling notebook, and expect 4 as return value

Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36
  • Bingo! It works as described. Thanks a lot! (sorry don't have enough reputation to upvote your answer...) – koch Jun 07 '17 at 16:02
  • thanks for explaining it well. Although i had to rerun %run notebook command two three times, before it actually registered the function in the current namespace. – Madhavi Jouhari Dec 16 '19 at 12:37