Yet another ImportError: attempted relative import with no known parent package

san*_*ica 12 python import package python-import

I have the following directory structure:

py_test
??? __init__.py
??? dir1
?   ??? __init__.py
?   ??? script1.py
??? dir2
    ??? __init__.py
    ??? script2.py
Run Code Online (Sandbox Code Playgroud)

In script2 I want to "import ..\script1".

What I tried in script2:

  1. Does not work

    from ..dir1 import script1
    ImportError: attempted relative import with no known parent package`
    
    Run Code Online (Sandbox Code Playgroud)
  2. Works

    import sys, os
    path2add = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'dir1')))
    if (not (path2add in sys.path)) :
        sys.path.append(path2add)
    
    Run Code Online (Sandbox Code Playgroud)

If I want to go with option 1, what is the simplest (i.e., with the least files) file/dir structure that makes it work? I am aware of this, but I wonder if creating that directory structure can be avoided, and still use type-1 import.

I am currently using this workaround, which uses type-2 import.

Related:

如何导入上面目录中的 Python 类?

从上一级目录(包)导入模块

从 Python 解释器运行时出现“ImportError:在没有已知父包的情况下尝试相对导入”

使用 importlib 动态导入包含相对导入的模块

如何在不同的python文件中导入变量

Apo*_*ian 4

正如评论中提到的,如果 目录是您的入口点,则尝试将模块导入目录将不起作用script2.py

如此链接中提到的,您包括

如果模块__name__不包含任何包信息(例如,将其设置为__main__),则将解析相对导入,就像该模块是顶级模块一样,无论该模块实际位于文件系统上的位置。

模块的__name__设置为__main__如果它是入口点,或者是您通过类似python script2.py.

任何这样运行的 python 模块都不再具有从更高目录导入文件所需的信息。

因此你有两个选择:

选项 1:继续使用解决方法sys.path.append

这将按照您想要的方式工作,但相当麻烦。

选项 2:将切入点置于顶层

假设您的包有多个需要运行的脚本,您可以创建一个新文件来导入这两个脚本script1script2然后根据命令行参数调用您想要的功能。然后,您将能够保留当前的目录结构,并使相对导入正常工作,而无需对sys.path.


归档时间:

查看次数:

6292 次

最近记录:

5 年 前