本文介绍了从子文件夹自动导入模块时,其导入失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几个类似的问题,特别是这似乎接近我想要的,但我无法理解为什么我仍然会得到ImportErrors。这是我的文件夹层次结构:

I've read through a couple of similar questions, notably this one about imp.load_module which seems to be close to what I want, but I can't understand why I'm still getting ImportErrors. Here is my folder hierarchy:

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

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

In main.py I have the following code. This is intended to search the thirdparty\ directory and load each module it finds. Each module is in its own separate directory.

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的。它有一行说:

The problem is that css.py happens to use its own subfolder that it loads stuff off of, utils. It has a line in it that says:

from utils import http

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

And that is where it fails. I get this error when I run 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 就好了。造成这种情况的原因是什么?

I'm stumped. css.py is self contained in its own folder, and when I run css.py separately it imports utils just fine. What is causing this?

推荐答案

也许你可以通过改变导入来解决这个问题:

Maybe you can solve this by changing the import to:

from .utils import http

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

Or by adding the folder you import to the Python Path:

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

当您在第三方中导入模块时,Python寻找模块的地方仍然是主目录。初始导入有效,因为你给了 imp.find_module 的正确路径,但之后Python不知道在哪里寻找模块。

When you import modules in thirdparty, the place Python looks for modules is still the main directory. The initial import works, because you give the right path to imp.find_module, but after that Python has no idea where to look for the modules.

这篇关于从子文件夹自动导入模块时,其导入失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:32