Python 从另一个 .ipynb 文件导入一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44116194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
import a function from another .ipynb file
提问by Chao Song
I defined a hello world function in a file called 'functions.ipynb'. Now, I would like to import functions in another file by using "import functions". I am sure that they are in the same folder. However, it still shows that "ImportError: No module named functions". By the way, I am using jupyter notebook. Thanks a lot!
我在名为“functions.ipynb”的文件中定义了一个 hello world 函数。现在,我想使用“导入函数”在另一个文件中导入函数。我确定它们在同一个文件夹中。但是,它仍然显示“ImportError: No module named functions”。顺便说一下,我正在使用 jupyter notebook。非常感谢!
回答by David Rinck
You'll want to use the ipynb package/module importer. You'll need to install it: pip install ipynb
.
您需要使用ipynb 包/模块导入器。您需要安装它:pip install ipynb
.
Create a Notebook named my_functions.ipynb
. Add a simple function to it.
创建一个名为 的笔记本my_functions.ipynb
。给它添加一个简单的函数。
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Then, create a second IPython Notebook and import this function with:
然后,创建第二个 IPython Notebook 并使用以下命令导入此函数:
from ipynb.fs.full.my_functions import factorial
Then you can use it as if it was in the same IPython Notebook:
然后你可以像在同一个 IPython Notebook 中一样使用它:
testing = factorial(5)
See the documentationfor more details.
有关更多详细信息,请参阅文档。