ModuleNotFoundError: No module named... importing from a sub-sub directory

ModuleNotFoundError: No module named... importing from a sub-sub directory

我无法从从子文件夹导入模块的子文件夹导入模块。我正在使用 python 3.6.

文件夹的结构如下所示:

src
├── script.py
└── prepare_data
          ├── __init__.py
          ├── test.py      
          └── lib
               ├── aspect_extraction.py
               └── __init__.py

而在 aspect_extraction.py 我这样做:

def aspect_extraction():
    print("ok this worked")

test.py 看起来像这样:

from lib.aspect_extraction import aspect_extraction
def test_func():
    aspect_extraction()

test_func()

script.py 看起来像这样:

from prepare_data.test import test_func
test_func()

当我运行pipenv run python src/script.py

File "/src/prepare_data/test.py", line 1, in <module>
from lib.aspect_extraction import aspect_extraction
ModuleNotFoundError: No module named 'lib'

奇怪的是,当我 运行 pipenv run python src/prepare_data/test.py 时,它起作用了。

ok this worked

我无法确定是什么问题...这与 python 版本有关吗?

test.py 中的导入语句在当前工作目录中查找 lib.aspect_extraction,即调用它的目录(通常是 script.py 所在的目录,但不一定)。最简单的解决方案(不是最好的):更改导入语句:

from prepare_data.lib.aspect_extraction import aspect_extraction
def test_func():
    aspect_extraction()

test_func()

您可以使用os.getcwd() 查看当前工作目录。这是您的第一个导入参考。

您还可以通过 os.path.dirname(os.path.abspath(file)) 获取正在运行的 python 文件。在 script.py 和 test.py 中插入这些行以检查差异:

import os
WORK_DIR = os.getcwd()
THIS_FILE_DIR = os.path.dirname(os.path.abspath(__file__))
print('WORK_DIR', WORK_DIR)
print('THIS_FILE_DIR', THIS_FILE_DIR)

有关 python 查找模块的位置的信息:

"The first thing Python will do is look up the module in sys.modules. This is a cache of all modules that have been previously imported.

If the name isn’t found in the module cache, Python will proceed to search through a list of built-in modules. These are modules that come pre-installed with Python and can be found in the Python Standard Library. If the name still isn’t found in the built-in modules, Python then searches for it in a list of directories defined by sys.path. This list usually includes the current directory, which is searched first."

https://realpython.com/absolute-vs-relative-python-imports/

中的更多内容

希望这对您有所帮助。