【发布时间】:2021-12-04 17:49:12
【问题描述】:
我希望能够从位于子文件夹中的测试脚本测试 python 类。我的项目结构如下:
importTest
__init__.py
testFolder
testScript.py
tobeimported.py
tobeimported.py的内容是:
class ToBeImported:
def __init__(self):
self.print('Created!')
我的 testScript.py 的内容是:
from ...importTest import tobeimported
def runTest():
item = tobeimported.ToBeImported()
if __name__ == '__main__':
runTest()
当我运行 testScript.py 时,我得到了错误:
attempted relative import with no known parent package
但是 importTest 应该被称为一个包,对吧?因为它有__init__.py 文件?
我还能如何在我的测试脚本中导入我的 ToBeImported 类?
我正在运行 python 3.9.5
【问题讨论】:
-
您可以在您的
__init__.py文件中添加from .tobeimported import ToBeImported并使用from importTest import ToBeImported -
@BijayRegmi:不,这不起作用。如果我尝试这个,运行 testScript.py 它会说:'没有名为 importTest 的模块。此外,这意味着
__init__.py必须根据每次导入的使用情况进行更改。从文档中我了解到该文件需要为空... -
如何运行脚本?
-
@Mr_and_Mrs_D:很抱歉我的回复晚了...我以 python3 -m importTest/testFolder/testScript.py 运行它。
标签: python-3.x python-import relative-import