我想将一个包导入到我的项目目录中的另一个包中

时间:2020-07-12 08:05:51

标签: python python-import python-module

我的项目结构是:

     project
     |--main
     |   |--__init_.py
     |   |-- file_to_be_imported.py
     |--tests
         |--conftest.py

我想将file_to_be导入到测试中的conftest中。

“包含正在运行的脚本的目录位于搜索路径的开始,位于标准库路径的前面。这意味着将加载该目录中的脚本,而不是库目录中具有相同名称的模块。除非打算进行更换,否则这是一个错误。” from The Module Search Path

所以我阅读了这份文件并使用:

import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

此代码在conftest中。一切正常。但是,如果不使用上面的代码片段,还有其他方法吗?

1 个答案:

答案 0 :(得分:-1)

您不需要使用该代码。您需要做的就是在您的 tests 目录中添加__init__.py。 您的项目将如下所示:

 project
 |--main
 |   |--__init__.py
 |   |-- file_to_be_imported.py
 |--tests
     |--__init__.py
     |--conftest.py

在conftest.py中,您只需从main导入代码

from main import file_to_be_imported
#Write test

编辑: 然后您像执行模块一样执行文件,而不是像常规python文件一样

python -m test.conftest

如果要像常规python文件一样执行它,则需要sys.path。