本文介绍了Python找不到本地模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的文件夹结构:

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找不到本地模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:14