来自同一文件夹的 python __import__ 失败

标签 python import importerror

我的目录结构是这样的:

|- project
  |- commands.py
  |- Modules
  | |- __init__.py
  | |- base.py
  | \- build.py
  \- etc....

我在__init__.py中有以下代码

commands = []
hooks = []

def load_modules():
    """ dynamically loads commands from the /modules subdirectory """
    path = "\\".join(os.path.abspath(__file__).split("\\")[:-1])
    modules = [f for f in os.listdir(path) if f.endswith(".py") and f != "__init__.py"]
    print modules
    for file in modules:
        try:
            module = __import__(file.split(".")[0])
            print module
            for obj_name in dir(module):
                try:
                    potential_class = getattr(module, obj_name)
                    if isinstance(potential_class, Command):
                        #init command instance and place in list
                        commands.append(potential_class(serverprops))
                    if isinstance(potential_class, Hook):
                        hooks.append(potential_class(serverprops))
                except:
                    pass
        except ImportError as e:
            print "!! Could not load %s: %s" % (file, e)
    print commands
    print hooks

我试图让 __init__.py 将适当的命令和 Hook 加载到给定的列表中,但是我总是在 module = __import__(file.split(".")[0]) 即使 __init__.py 和 base.py 等都在同一个文件夹中。我已验证任何模块文件中的任何内容都不需要 __init__.py 中的任何内容,所以我真的不知道该怎么做。

最佳答案

您所缺少的只是系统路径上的模块。添加

import sys
sys.path.append(path)

在你的 path = ... 行之后,你应该被设置。这是我的测试脚本:

import os, os.path, sys

print '\n'.join(sys.path) + '\n' * 3

commands = []
hooks = []

def load_modules():
    """ dynamically loads commands from the /modules subdirectory """
    path = os.path.dirname(os.path.abspath(__file__))

    print "In path:", path in sys.path
    sys.path.append(path)

    modules = [f for f in os.listdir(path) if f.endswith(".py") and f != "__init__.py"]
    print modules
    for file in modules:
        try:
            modname = file.split(".")[0]
            module = __import__(modname)
            for obj_name in dir(module):
                print '%s.%s' % (modname, obj_name )
        except ImportError as e:
            print "!! Could not load %s: %s" % (file, e)
    print commands


load_modules()

关于来自同一文件夹的 python __import__ 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496156/

相关文章:

python - 如何使 Plotly 饼图始终大小相同

python - 在 RGB 图像的 tensorflow 中使用 SSIM 损失函数

javascript - EcmaScript 模块 (JavaScript) 中的延迟导出

c++ - OpenGL Assimp 导入模型不渲染

python - 在python中使用ast.literal_eval(open (“filename”).readlines()[0])的语法错误

python - 尝试导入嵌套模块时 Python 中出现 ModuleNotFound 错误

Python 嵌套范围函数

python - 为什么当我 append 到元组内部的列表时,元组的内容会发生变化,但当我更新变量时却不会发生变化?

mysql - 无法从 mysql.proc 加载。该表可能已损坏

image - scipy.misc 图像函数(例如 imread、imresize、imsave、imshow 等)上的 AttributeError、ImportError