【问题标题】:When automatically importing modules from a subfolder, their imports fail从子文件夹自动导入模块时,它们的导入失败
【发布时间】:2011-06-26 07:08:28
【问题描述】:

我已经阅读了几个类似的问题,尤其是this one about imp.load_module,这似乎与我想要的很接近,但我不明白为什么我仍然收到 ImportErrors。这是我的文件夹层次结构:

program\
  __init__.py
  main.py
  thirdparty\
    __init__.py
    css\
      __init__.py
      css.py
      utils\
        __init__.py
        http.py

main.py 我有以下代码。这是为了搜索thirdparty\ 目录并加载它找到的每个模块。每个模块都在自己的单独目录中。

import os
import imp

for root, dirs, files in os.walk("thirdparty"):
    for source in (s for s in files if s.endswith(".py")):
        name = os.path.splitext(os.path.basename(source))[0]
        m = imp.load_module(name, *imp.find_module(name, [root]))

问题是css.py 碰巧使用了它自己的子文件夹utils。里面有一行写着:

from utils import http

这就是失败的地方。运行 main.py 时出现此错误。

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    m = imp.load_module(name, *imp.find_module(name, [root]))
  File "thirdparty/css/css.py", line 1, in <module>
    from utils import http
ImportError: No module named utils

我被难住了。 css.py 包含在自己的文件夹中,当我单独运行 css.py 时,它导入 utils 就好了。这是什么原因造成的?

【问题讨论】:

  • 我遇到了同样的问题。你有没有找到答案?在 Python 3 中,不推荐使用 imp 模块以支持 importlib,但我还没有尝试过。

标签: python python-import relative-path python-packaging


【解决方案1】:

也许您可以通过将导入更改为:

from .utils import http

或者通过将您导入的文件夹添加到 Python 路径:

sys.path.append(os.path.join(root, source))

当您在thirdparty 中导入模块时,Python 查找模块的位置仍然是主目录。初始导入有效,因为您提供了指向 imp.find_module 的正确路径,但之后 Python 不知道在哪里查找模块。

【讨论】:

    猜你喜欢
    • 2012-02-15
    • 1970-01-01
    • 2013-03-25
    • 2012-12-13
    • 2017-06-07
    • 2021-06-02
    • 2013-08-26
    • 2019-09-16
    相关资源
    最近更新 更多