1

你能告诉我如何正确地进行相对导入吗?

项目结构:

p1
|-  x1
|  |-  __init__.py
|  |-  x1_module1.py
|- x2
   |-  __init__.py
   |-  x2_module1.py

在 x2_modules.py

try:
    from p1.x1.x1_module import temp_func
except Exception as e:
    print('Failed "from p1.x1.x1_module import temp_func"')
    print(e)

try:
    from .x1.x1_module import temp_func
except Exception as e:
    print('Failed "from .x1.x1_module import temp_func"')
    print(e)

try:
    from ..x1.x1_module import temp_func
except Exception as e:
    print('Failed "from ..x1.x1_module import temp_func"')
    print(e)

输出:

Failed "from p1.x1.x1_module import temp_func"
No module named 'p1'
Failed "from .x1.x1_module import temp_func"
attempted relative import with no known parent package
Failed "from ..x1.x1_module import temp_func"
attempted relative import with no known parent package
[Finished in 0.2s]

想了解更多,请看这张图: 在此处输入图像描述

4

2 回答 2

0

项目结构:

p1
|-  x1
|  |-  __init__.py
|  |-  x1_module1.py
|- x2
   |-  __init__.py
   |-  x2_module1.py

编辑:代码没有遵循 PEP-8 并且难以阅读。因此,我对其进行了优化。

请尝试以下代码:

import sys
import os

PACKAGE_PARENT = '..'

SCRIPT_DIR = os.path.dirname(
    os.path.realpath(
        os.path.join(
            os.getcwd(),
            os.path.expanduser(__file__)
            )
        )
    )

sys.path.append(
    os.path.normpath(
        os.path.join(
            SCRIPT_DIR,
            PACKAGE_PARENT
            )
        )
    )

from x1.x1_module import tempfunction

有用

问候伊沙恩·卡普尔

于 2020-10-24T05:37:57.137 回答
0

如果从 p1 目录调用您的 python 脚本,这应该可以工作:

from x1.x1_module1 import temp_func

要查看 python 在哪里搜索您的模块的列表,请使用以下命令:

import sys
print(sys.path)

sys.path 的第一个条目应该是运行脚本的目录,我假设它是 p1

于 2020-10-24T06:04:37.003 回答