[英]What is the correct way to import modules/packages for Python projects with unit tests?
I have the following directory structure: 我有以下目录结构:
|_ director_script.py
|_ app/
|_ __init__.py
|_ ParentClass.py
|_ my_module/
|_ __init__.py
|_ MyClass.py
|_ MyClassTestCase.py
In my director_script.py
I use MyClass
and when I run python director_script.py
the scripts run as expected without any error. 在我的director_script.py
我使用MyClass
,当我运行python director_script.py
,脚本按预期运行,没有任何错误。 However, when I cd into my_module
folder and run the unit tests using python -m unittest MyClassTestCase
, I get the error: 但是,当我进入my_module
文件夹并使用python -m unittest MyClassTestCase
运行单元测试时,出现错误:
ModuleNotFoundError: No module named 'app'
This caused by the import statement in MyClass.py
that is 这是由MyClass.py
中的import语句引起的,即
from app.ParentClass import ParentClass
This import is fine when I run it from director_script.py
and only happens with the unit test. 当我从director_script.py
运行它时,这种导入很好,并且仅在单元测试中发生。
You should run from outside the app folder, any folder that has an __init__.py
is a submodule in python. 您应该从app文件夹之外运行,任何具有__init__.py
文件夹都是python中的子模块。 If you set the current working directory to my_module, it cannot see the app module, unless you have the folder path corresponding to the app folder set in the PYTHONPATH
environment variable 如果将当前工作目录设置为my_module,则它将看不到应用程序模块,除非您具有与PYTHONPATH
环境变量中设置的应用程序文件夹相对应的文件夹路径
在顶层文件夹中添加一个名为__init__.py
的文件
A bit of a kludge, but this is how I usually do it: 有点纠结,但这是我通常的做法:
import sys
sys.path.append('../app')
Or under Windows: 或在Windows下:
sys.path.append('..\\app')
This needs to come before your module import, of course. 当然,这需要在模块导入之前进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.