问题描述
我有一个像这样的文件夹结构:
I have a folder structure like this:
setup.py
core/
__init__.py
interpreter.py
tests/
__init__.py
test_ingest.py
如果我尝试在test_ingest.py
中导入core
并运行它,我会得到一个ImportError
,说找不到core
模块.但是,我可以将core
导入到setup.py
中而不会出现问题.我的IDE并不奇怪,那么为什么会发生此错误?
If I try to import core
in test_ingest.py
and run it, I get an ImportError
saying that the core
module can't be found. However, I can import core
in setup.py
without an issue. My IDE doesn't freak out, so why is this error occurring?
推荐答案
在打包import
时,Python搜索sys.path
上的目录,直到找到以下目录之一:名为"core.py"的文件,或者名为核心"的目录,其中包含名为__init__.py
的文件.然后,Python 导入您的包.
When you import
your package, Python searches the directories on sys.path
until it finds one of these: a file called "core.py", or a directory called "core" containing a file called __init__.py
. Python then imports your package.
您可以从setup.py
成功地import core
,因为在sys.path
中找到了core
目录的路径.您可以通过运行文件中的以下代码片段来自己查看:
You are able to successfully import core
from setup.py
because the path to the core
directory is found in sys.path
. You can see this yourself by running this snippet from your file:
import sys
for line in sys.path:
print line
如果要从文件夹结构中的其他文件导入core
,则可以将路径添加到在文件中的sys.path
中找到core
的目录:
If you want to import core
from a different file in your folder structure, you can append the path to the directory where core
is found to sys.path
in your file:
import sys
sys.path.append("/path/to/your/module")
这篇关于Python找不到本地模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!