在Python中,添加导入根路径后无法导入当前模块

In Python, cannot import current modules after adding the importing root path

我下面有一个项目。

project/
├ main/
  ├ modules/
    ├ moduleA.py
├ test/
  ├ testA.py
  ├ modules/
    ├ moduleC.py

我在下面编写了 moduleA.pymoduleC.py

# moduleA.py
def funcA():
  print("A")
# moduleC.py
def funcC():
  print("C")

在我想在 testA.py 中使用 moduleC.funcC() 测试 moduleA.funcA() 的情况下,我担心代码将 moduleC.funcC() 导入 testA.py .

import inspect
import os
import sys
PYPATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/"
sys.path.append(PYPATH + "./../")
from main.modules.moduleA import funcA # This is OK.

# from test.modules.moduleC import funcC # ModuleNotFoundError
from modules.moduleC import funcC # This is OK.

if __name__ == "__main__":
  funcA()
  funcC()

我想用 from test.modules.moduleC import funcCfuncC() 导入到 testA.py

你说这个可行吗?

是的,它完全可行。 Python 定义了两种类型的包,常规包和命名空间包。常规包是 Python 3.2 及更早版本中存在的传统包。常规包通常实现为包含“init.py”文件的目录。当导入一个常规包时,这个'init.py'文件被隐式执行,它定义的对象被绑定到包命名空间中的名称。 'init.py' 文件可以包含任何其他模块可以包含的相同 Python 代码,并且 Python 会在模块运行时向模块添加一些额外的属性已导入。

因为python已经有一个名为test的模块,而python中没有modules模块的测试。因此,将 test 目录重命名为其他名称即可。或更改 sys.path 的默认顺序