Python can't find local module

风格不统一 提交于 2019-12-10 18:13:05

问题


I have a folder structure like this:

setup.py
core/
    __init__.py
    interpreter.py
tests/
    __init__.py
    test_ingest.py

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?


回答1:


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.

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

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")


来源:https://stackoverflow.com/questions/38135119/python-cant-find-local-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!