简体   繁体   English

相同的笔记本无法导入模块

[英]Identical Notebook can't import module

I have two identical Jupyter Notebooks in two different folders. 我在两个不同的文件夹中有两个相同的Jupyter笔记本。 If I fire up jupyter notebooks and open one of the notebooks, and run the cell with: 如果我启动jupyter笔记本并打开其中一个笔记本,然后使用以下命令运行单元:

import example_name

it loads just fine. 它加载很好。

If I open the identical notebook in the other folder and try running the same: 如果我在另一个文件夹中打开相同的笔记本并尝试运行相同的笔记本:

import example_name

I get error message: 我收到错误消息:

ImportError: No module named example_name

What could explain this and how do I track down the filepath to 'example_name' in the notebook where it loads fine? 有什么能解释这个问题,以及如何在加载正常的笔记本中找到“ example_name”的文件路径?

You're trying to import a module named example_name from the directory in which the notebook resides ./ - the module - a file called example_name.py - exists in one of the directories but not the other. 你试图导入名为模块example_name从该笔记本所在的目录./ -模块-一个名为example_name.py -存在于目录中的一个而不是其他。

The issue is related python sys.path which tells the python interpreter where to load python modules from, you can print this list of directories and you should see an entry for . 问题与python sys.path有关,它告诉python解释器从何处加载python模块,您可以打印此目录列表,并且应该看到的条目. - which is the current directory and a bunch of other directories. -这是当前目录和其他目录。

You can either copy the example_name.py file along with the notebook or add the directory path of example_name.py to sys.path using sys.path.append('/some/path') . 您可以将example_name.py文件与笔记本一起复制,也可以使用sys.path.append('/some/path')example_name.py的目录路径添加到sys.path

To do this correctly you would actually have a directory on your computer which contains all the scripts you need in your notebooks, and add that directory path to the PYTHONPATH environment variable. 要正确执行此操作,您实际上将在计算机上拥有一个目录,其中包含笔记本中所需的所有脚本,然后将该目录路径添加到PYTHONPATH环境变量中。 That way the directory will always be added to sys.path . 这样,目录将始终添加到sys.path

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

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