python - 另一个 ImportError : attempted relative import with no known parent package

标签 python import package python-import

这个问题在这里已经有了答案:





Attempted relative import with no known parent package

(3 个回答)



Relative imports in Python 3

(24 个回答)


8 个月前关闭。




我有以下目录结构:

py_test
├── __init__.py
├── dir1
│   ├── __init__.py
│   └── script1.py
└── dir2
    ├── __init__.py
    └── script2.py

script2我想“import ..\script1”。

我在 script2 中尝试过的内容:
  • 不工作
    from ..dir1 import script1
    ImportError: attempted relative import with no known parent package`
    
  • 作品
    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)
    

  • 如果我想使用选项 1,使其工作的最简单(即文件最少)的文件/目录结构是什么?
    我知道 this ,但我想知道是否可以避免创建该目录结构,并且仍然使用 type-1 import .

    我目前正在使用 this workaround , 它使用类型 2 import .

    有关的:

    How to import a Python class that is in a directory above?

    Import a module from a directory (package) one level up

    Getting "ImportError: attempted relative import with no known parent package" when running from Python Interpreter

    Using importlib to dynamically import module(s) containing relative imports

    How to import variables in a different python file

    最佳答案

    如评论中所述,尝试将模块导入目录将不起作用如果 script2.py是你的切入点。
    this link you included 中所述:

    If the module's __name__ does not contain any package information (e.g., it is set to __main__), then relative imports are resolved as if the module were a top-level module, regardless of where the module is actually located on the file system.


    该模块的__name__设置为 __main__如果它是入口点,或者是你传递给解释器的入口点,比如 python script2.py .
    这样运行的任何 python 模块都不再具有从更高目录导入文件所需的信息。
    因此,您有两种选择:
    选项 1:继续使用 sys.path.append 的解决方法
    这将按照您的意愿工作,但它相当麻烦。
    选项 2:将您的入口点放在顶层
    假设你的包有多个脚本需要运行,你可以创建一个新文件来导入 script1script2然后根据命令行参数调用您想要的功能。然后你就可以保持你当前的目录结构并且让你的相对导入工作得很好,而不需要对 sys.path 进行任何摆弄。 .

    关于python - 另一个 ImportError : attempted relative import with no known parent package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59489786/

    相关文章:

    python - Airflow 运算符(operator)是否需要返回任何内容才能正常运行?

    python - 如何在 Python Zope 服务器中配置数据库连接池

    python-3.x - 在 Python 3 中从同一包内和包外导入模块

    python - 如何防止python模块被另一个脚本导入

    python - Python 如何从 .egg 文件中导入模块?

    linux - 检查 bash 的安装包

    python - 将字典转换为具有波斯字符的 json

    python - Raspberry Pi 3 通过 720p USB 摄像头提高 FPS

    python - 记录导入模块所花费的时间

    Java 全局命名空间访问