我有一个包和一个测试包。根据Where do the Python unit tests go?的建议,测试应该位于不同的目录中。项目的目录树如下:
project\
kernel\
__init__.py
file1.py
file2.py
tests\
__init__.py
test1.py
test2.py
test3.py
我想将 kernel
包导入到 tests
包中,因为这是 file1.py
和 file2.py 所在的位置。 py
正在测试。另外,我想在 __init__.py
中使用一个 import
语句,而不是在每次测试中一次又一次地导入 kernel
。
我尝试将以下内容添加到 tests
中的 __init__.py
文件和 test2.py
、 test2.py
(一起和单独),没有成功(第一个没有害处,第二个给出语法错误):
import kernel
import ../kernel
我使用的是python2.6。从命令行发生上述所有事情。当我使用 Eclipse PyDev 时,一切都神奇地工作了。
最佳答案
您使用的相对导入仅在“project”目录是 python 包(即其中包含 __init__.py
文件)时才有效。首先尝试一下,看看是否适合您。
如果 kernel
目录充当要分发的“包”,那么您可以将 tests
目录放入其中,并以这种方式进行相对导入。所以它看起来像这样:
project/
kernel/
__init__.py
file1.py
file2.py
tests/
__init__.py
test1.py ...
您可以从测试目录导入内核模块,如下所示:
from kernel import file1 # if it's installed in the python path/environment
或者:
from .. import file1
# 'import ..file1' might work, but I'm not sure that's syntactically correct
关于python - 将 __init__.py 导入到unittest包中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24210651/