在 Jupyter Notebook 中导入期间未找到模块 [英] Module Not found during import in Jupyter Notebook

查看:73
本文介绍了在 Jupyter Notebook 中导入期间未找到模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下包(和工作目录):

I have the following package (and working directory):

WorkingDirectory--
                 |--MyPackage--
                 |            |--__init__.py
                 |            |--module1.py
                 |            |--module2.py
                 |
                 |--notebook.ipynb

__init__.py 我有:

import module1
import module2

如果我尝试将 MyPackage 导入我的笔记本:

If I try to import MyPackage into my notebook:

import MyPackage as mp 

我会收到ModuleNotFoundError: No module named 'module1'.但如果我在笔记本外执行脚本,导入工作正常:如果我在同一目录中创建 test.py 并在笔记本中执行相同的操作,导入将正常工作.如果我在 __init__.py (import MyPackage.module1) 中使用完全限定名称,它将在笔记本内工作.

I will get ModuleNotFoundError: No module named 'module1'. But import works fine if I execute the script outside a notebook: if I create test.py in the same directory and do the same as in the notebook the import would work properly. It will work inside the notebook if I use fully qualified name in __init__.py (import MyPackage.module1).

导入行为不同的原因是什么?

What's the reason for different import behavior?

我已经确认笔记本的工作目录是WorkingDirectory.

I have confirmed the working directory of the notebook is WorkingDirectory.

---更新---------

---Update---------

确切的错误是:

C:UsersMeDocumentsWorking DirectoryMyPackage\__init__.py in <module>()
---> 17 import module1

ModuleNotFoundError: No module named 'module1'

我的问题与可能的重复不同:

My problem differs from the possible duplicate:

  1. 笔记本能够找到包,但无法加载模块.这是通过将 module1 替换为 MyPackage.module1 推断出来的,效果很好,并表明这可能不是与 PATH 相关的问题.

  1. The notebook was able to find the package, but only unable to load the module. This was inferred from substituting module1 with MyPackage.module1 worked well and suggests it may not be a problem related with PATH.

我进入 WorkingDirectory 并在那里启动服务器.工作目录应该是包含我的包的文件夹.

I cded into WorkingDirectory and started the server there. The working directory should be the folder containing my package.

推荐答案

我很确定这个问题是相关的,那里的答案会帮助你:https://stackoverflow.com/a/15622021/7458681

I'm pretty sure this issue is related and the answer there will help you: https://stackoverflow.com/a/15622021/7458681

tl;dr 笔记本服务器的 cwd 始终是您启动服务器的基本路径,无论是否运行 import os os.getcwd() 说.使用 import sys sys.path.append("/path/to/your/module/folder").

tl;dr the cwd of the notebook server is always the base path where you started the server, no matter was running import os os.getcwd() says. Use import sys sys.path.append("/path/to/your/module/folder").

我用一些与你指定的结构相同的虚拟模块运行它,在修改 sys.path 之前它不会运行,之后它会

I ran it with some dummy modules in the same structure as you had specified, and before modifying sys.path it wouldn't run and after it would

这篇关于在 Jupyter Notebook 中导入期间未找到模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆