Python 如何将 jupyter notebook 目录中的模块导入较低目录中的 notebooks?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39299838/
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
How do I import module in jupyter notebook directory into notebooks in lower directories?
提问by James Draper
I have used jupyter notebook for data analysis for quite sometime. I would like to develop a module in my jupyter notebook directory and be able to import that new module into notebooks. My jupyter notebook file directory can be represented as follows;
我使用 jupyter notebook 进行数据分析已经有一段时间了。我想在我的 jupyter notebook 目录中开发一个模块,并且能够将该新模块导入到 notebooks 中。我的jupyter notebook文件目录可以表示如下;
Jupyter notebooks\
notebook1.ipynb
new_module\
__init__.py
newfunction.py
currentnotebooks\
notebook2.ipynb
When use import new_modulein notebook1.ipynb it works however when I try the same command in notebook2.ipynb I get the following ImportError: No module named 'new_module'. The two obvious solutions are A) move new_module into the currentnotebooks directory or B) move notebook2.ipynb up to the same level as new_module. I don't want to mess around with the file structure at all. Is this possible?
import new_module在 notebook1.ipynb 中使用时,它可以工作,但是当我在 notebook2.ipynb 中尝试相同的命令时,我得到以下信息ImportError: No module named 'new_module'。两个明显的解决方案是 A) 将 new_module 移动到 currentnotebooks 目录或 B) 将 notebook2.ipynb 移动到与 new_module 相同的级别。我根本不想弄乱文件结构。这可能吗?
回答by cco
You need to make sure that the parent directory of new_moduleis on your python path. For a notebook that is one level below new_module, this code will do the trick:
您需要确保 的父目录new_module在您的python 路径上。对于低于 1 个级别的笔记本new_module,此代码将起作用:
import os
import sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
sys.path.append(nb_dir)
If you're further down in the directory hierarchy, you will need to adjust the way nb_diris set, but that's all. You should notrun this code for a notebook in Jupyter notebooks, since it would add the parent of that directory to the python path, which is probably undesirable.
如果您在目录层次结构中更靠后,则需要调整设置方式nb_dir,仅此而已。你应该不是在笔记本运行这段代码Jupyter notebooks,因为这将是目录的父目录添加到Python路径中,这可能是不可取的。
The reason the import works for notebook1is that sys.path contains ''(the empty string), which is aways the current directory of the running interpreter (kernel, in this case). A google search for explain python pathturns up several good explanations of how python uses PYTHONPATH(aka sys.path).
导入工作的原因notebook1是 sys.path 包含''(空字符串),它远离正在运行的解释器(在这种情况下为内核)的当前目录。谷歌搜索找到explain python path了关于 python 如何使用的几个很好的解释PYTHONPATH(又名sys.path)。

