简体   繁体   English

导入错误:尝试在没有已知父项的情况下进行相对导入 package

[英]Import Error : attempted relative import with no known parent package

Can you please tell me how to do relative import correctly.你能告诉我如何正确地进行相对导入吗?

Project Structure:项目结构:

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

In x2_modules.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)

Output: Output:

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]

For more understanding, please take a look at this image:为了更好地理解,请看这张图片: 在此处输入图像描述

Project Structure:项目结构:

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

Edit: The code wasn't following PEP-8 and was hard to read.编辑:代码不遵循 PEP-8 且难以阅读。 I, thus, optimized it.因此,我对其进行了优化。

Please try this code:请试试这段代码:

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

It works有用

Regards Ishaan Kapoor问候伊沙恩·卡普尔

If your python script is called from the p1 directory, this should work:如果您的 python 脚本是从 p1 目录调用的,这应该有效:

from x1.x1_module1 import temp_func

To see a list of where python is searching for your module, use this:要查看 python 在何处搜索您的模块的列表,请使用以下命令:

import sys
print(sys.path)

The first entry of sys.path should be the directory your script is running from, which I'm assuming is p1 sys.path 的第一个条目应该是你的脚本运行的目录,我假设是 p1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM