Python 不会从导入另一个文件夹的同一文件夹中导入模块



所以我有一个这样的项目

root/
api/
nest/
nest.py
tests.py
__init__.py

当我运行python nest/nest.py -args时它工作正常,但是当我运行python nest/tests时.py它崩溃,说我在 tests.py
ModuleNotFoundError: No module named 'nest.nest'; 'nest' is not a package中存在导入错误

我的 tests.py 导入如下所示

import unittest
from nest.nest import JsonParser

我也在 api/api .py 模块中使用这个 JsonParser 类,它工作正常 除此之外,如果我在 pycharm 中运行 tests.py 它可以正常工作,但如果我在控制台中尝试,它会抛出此异常

问题是您的 interprerter 在模块范围之外运行时不知道该模块所在的路径。

解决方案可能是在代码中添加模块的绝对路径:

import sys
sys.path.append('my/path/to/module/folder')
import module-of-interest

最新更新