从python中的不同目录导入

2024-10-01 13:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的文件夹结构:

src/
  __init__py
  Lowlevel/
    __init__.py
    ModuleToCheck.Py
  Test/
    __init__.py
    ModuleToCheck_test.py

__init__.py为空文件)

现在我想导入ModuleToCheck.pyModuleToCheck_test.py

我如何才能做到这一点而不在sys.path上添加任何内容?在


更新:

from ..Lowlevel import ModuleToCheck导致:

^{pr2}$

Tags: 文件pathfrompytestsrc文件夹内容
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:04

以下内容来自http://docs.python.org/tutorial/modules.html#intra-package-references

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

您将模块ModuleToCheck_test.py作为主模块运行,因此出现异常。在

一种解决方案是在src目录中创建一个test.py模块,其中包含以下内容:

import Test.ModuleToCheck_test

然后可以使用python test.py运行该模块

相关问题 更多 >