【问题标题】:Importing a module from a python file calling other modules从调用其他模块的python文件导入模块
【发布时间】:2019-11-19 08:42:32
【问题描述】:

我正在尝试运行特定代码,现在它需要以下 Python 文件的导入并且我收到错误消息,我构建了一个玩具示例来说明问题。我在 Python 3.6.3 版上运行。
考虑以下文件夹结构。

root
  |- outside.py
  |- folA
       |- __init__.py
       |- inside.py
       |- folB
            |- __init__.py
            |- eveninside.py

现在这些文件的内容如下。

outside.py

import folA.inside
print("Outside")


inside.py

import folB.eveninside
print("Inside")


eveninside.py

print("Even Inside")   #All inits are empty


现在,当我运行 inside.py 时,一切都运行得非常好并且有预期的输出。 但是当我运行 outside.py 时,会出现“没有名为 folB 的模块”的错误。我已尝试附加系统路径,但没有任何更改。请解释一下如何解决这个问题。

【问题讨论】:

    标签: python python-3.x module importerror


    【解决方案1】:

    这只是因为 python 从 python 路径中查找模块。在这里,当您在外面启动时,他会尝试查看您的目录中是否有一个 folB,其中是 outside.py。

    两种解决方案。

    1. 您在 inside.py 中使用sys.path.append 将 folA 所在的目录添加为尝试导入模块时要查找的位置。我不知道这是多么好的做法。

    2. 在您的情况下,您可以只写 inside.py `import folA.folB.eveninside。但很明显,当你启动 inside.py 时它不会工作。在这种情况下,您有第一个解决方案。

    【讨论】:

    • 第二种导入folA.folB.eveninside方法有效,第一种方法无效,仍然出现导入错误。
    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多