简体   繁体   English

从jupyter笔记本调用不同文件中编写的函数

[英]Call a function written in different file from jupyter notebook

From a jupyter notebook, I'd like to call a function written in another .ipynb file. 从一个jupyter笔记本,我想调用另一个.ipynb文件编写的函数。 The partial answer is given in this thread Reusing code from different IPython notebooks by drevicko . 部分答案在此线程中给出了重用来自 drevicko的 不同IPython笔记本代码 As an example, I'm using plus_one function written in plus_one.ipynb : 举个例子,我使用plus_one写在功能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 . 我的预期产量是4 How to pass an argument ( 3 ) to this script? 如何将参数( 3 )传递给此脚本? Thanks! 谢谢!

From the %run? %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 这类似于在系统提示符下运行python file args ,但其优点是可以为您提供IPython的回溯,并将所有变量加载到交互式命名空间中以供进一步使用

so all the cells from plus_one.ipynb are run and all it's variables are added to the namespace of the calling notebook. 所以来自plus_one.ipynb所有单元格plus_one.ipynb被运行,并且它的所有变量都被添加到调用笔记本的命名空间中。 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 这不直接调用plus_one方法(除非在另一个笔记本中调用),但它在当前命名空间中定义它,有点像常规python脚本中的import 。从那一刻开始,你应该能够在调用笔记本中执行plus_one(3) ,并期望4作为返回值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM