【问题标题】:Relative import of module in parent directory父目录中模块的相对导入
【发布时间】: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


【解决方案1】:

这里有两个问题

  • testFolder 中没有 __init__.py 文件,因此就 python 而言,这不是 python 包
  • testScript.py 直接从其文件夹运行。这使得python认为顶级包是testFolder所以“没有已知的父包”

您应该添加初始化文件,然后从 importTest 的父文件夹中以python -m importTest.testFolder.testScript 运行代码

【讨论】:

  • 非常感谢!我从来不知道你可以像这样运行包的一部分。这确实有效!
猜你喜欢
  • 2012-05-28
  • 1970-01-01
  • 2015-07-23
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多