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!
If you expand the files tab in Colab you can navigate to the files in Google Drive. Then you can right click on the file or folder you want and do Copy path . You can then paste this into the cell where path_to_module is defined.
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
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