Skip to main content
 首页 » 编程设计

python之导入 __init__.py 到 unittest 包

2024年11月01日13小虾米

我有一个包和一个测试包。根据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 正在测试中。另外,我想在 __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