【问题标题】:Package Imports in PythonPython 中的包导入
【发布时间】:2018-11-24 23:41:39
【问题描述】:

我对 Python 很陌生,但是当有人尝试推荐我使用包时,我遇到了这个问题。我的目录(不是实际名称,只是为了举例)如下:

Main_Folder
   - First_folder
       __init__.py
       first_file.py
   - Second_folder
       __init__.py
       second_file.py
   __init__.py
   third_file.py

我想使用我在 first_file 中的 second_file 中创建的一些函数,所以我写了两个(在不同的时间,不一样):

from .first_folder import first_file
from Main_Folder.first_folder import first_file

我收到如下错误:

<from first import>
ModuleNotFoundError: No module named '__main__.first_file'; '__main__' is not a package
<from second import>
ModuleNotFoundError: No module named 'Main_Folder'

但是,当我将third_file 导入到使用中的任何文件时,它可以工作:

from First_folder.first_file import some_function

所以我只是想知道我是否做错了什么。 我知道有很多这样的问题存在,我已经看过了,但是我什么都做不了。我也是 Python 的新手...

更新: 我使用它们的完整绝对路径运行这两个代码

【问题讨论】:

  • 这可能取决于你执行代码时所在的目录
  • 您到底在运行什么以及从哪个目录运行?您使用的是哪个版本的 Python? PEP 328 给你一个关于问题的提示,似乎__main__ 被设置为顶级模块(另见this question)。但是我看不出你是如何通过 .. 相对导入得到这个的,因为你应该得到 ValueError: attempted relative import beyond top-level package
  • 如果您坐在Main_Folder 中并在third_file.py 中使用from .first_folder import first_file(请注意单个.)并运行python third_file.py,那么这完美地解释了报告的错误(如由PEP 328).
  • 感谢您的回答,我正在运行 second_file.py。而且,你是对的,它只是一个点 (.),我使用两个点得到了这个错误。
  • 我也在 Main_Folder 和 Second_Folder 上运行了我的代码,但仍然遇到同样的错误..

标签: python python-import


【解决方案1】:

实现此功能的一种方法是将父路径添加到 python 路径,如下所示:

import sys
sys.path
sys.path.append('..')

那么你应该可以正常导入

【讨论】:

    【解决方案2】:

    我真的很喜欢这里对相对包导入的描述:https://docs.python.org/3/reference/import.html#package-relative-imports(第 5.7 点)。在您的情况下,这应该有效:

    from ..first_folder.first_file import first_function

    from ..first_folder import first_file

    【讨论】:

      猜你喜欢
      • 2010-09-30
      • 2012-02-21
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多