[英]Python module can't be imported from package
I have a package/module structure as follows:我有一个包/模块结构如下:
root/
├ aa
│ └──bb
│ └──b.py
├ cc
│ └──bb
│ └──b.py
In IPython I'm trying to import b
from aa.bb
like so:在 IPython 我试图从
aa.bb
导入b
像这样:
import sys
sys.path.append('/path/to/root/')
from aa.bb import b
But I am getting a ModuleNotFoundError但我收到 ModuleNotFoundError
ModuleNotFoundError: No module named 'aa.bb'
Importing just aa
works, as does importing cc.bb.b
:只导入
aa
有效,导入cc.bb.b
:
import sys
sys.path.append('/path/to/root/')
import aa
from cc.bb import b
What might be causing the module to be ignored, and how can I debug this?什么可能导致模块被忽略,我该如何调试? I suspect this is due to some mechanism at play in my IPython setup but don't know where to look.
我怀疑这是由于我的 IPython 设置中的某些机制在起作用,但不知道在哪里看。
have you tried using你有没有试过使用
import aa.bb.b
this has worked for me, or for a specific function in b.py you can use这对我有用,或者对 b.py 中的特定函数有用
from aa.bb.b import func
here is also a link to another stack overflow post about a similar topic: Importing files from different folder这里还有一个链接到另一个关于类似主题的堆栈溢出帖子: 从不同文件夹导入文件
It seems that a different aa
module is being loaded on startup.似乎在启动时加载了不同的
aa
模块。
In a fresh shell you can check out the imported modules with sys.modules.keys()
and find that aa
is already there.在新的 shell 中,您可以使用
sys.modules.keys()
检查导入的模块,并发现aa
已经存在。 You can see the source location using importlib
:您可以使用
importlib
查看源位置:
importlib.util.find_spec('aa')
> ModuleSpec(name='aa', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f8f5c8dd0>, origin='/not/the/right/path/aa', submodule_search_locations=['/not/the/right/path/aa'])
You can reload the loaded module using importlib
after ensuring a correct sys.path
, which should load the target module:您可以在确保正确的
sys.path
后使用importlib
重新加载加载的模块,这应该加载目标模块:
import importlib
importlib.reload(aa)
from aa.bb import b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.