为什么我在项目中遇到模块导入错误。所有包都在项目下,它们都有 __init __.py 并且其他脚本不会给出相同的错误。 Python版本是3.6。代码是在Unix环境下编写的。
这是我收到的导入错误。我正在尝试在这里运行测试。
Ran 1 test in 0.001s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/lib/python3.6/unittest/case.py", line 605, in run
testMethod()
File "/usr/lib/python3.6/unittest/loader.py", line 34, in testFailure
raise self._exception
ImportError: Failed to import test module: test_SMSHandler
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
File "/home/sevvalboylu/server/app/api/test_SMSHandler.py", line 11, in <module>
from middleware.services import Sender
ModuleNotFoundError: No module named 'middleware'
最佳答案
看起来您在 PYTHONPATH 中缺少项目的根路径
来自文档 ( Modules - The Module Source Path )
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
如果此解决方案不适合您,请发布项目树以便更轻松地找到问题。
关于Python 导入错误 - 运行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376731/